Core Data (CRUD)

 

Core data


Developer who are new to core-data always has a query, what is difference between Core-Data & Sql Lite? What should we use? 

Here is an answer for that: 

SQLite: 
  • Have data constraints feature
  • Operates on data, stored on disk
  • Can drop table and edit data without loading them in memory
  • Slow as compared to core data
Core Data:
  • Operates on memory
  • Data needs to be loaded from disk to memory to do any operations
  • Fast in terms of record creation (saving may be time consuming)



Main elements
  • ViewContext
  • NSManageObject
  • NSEntity
  • NSFetchRequest
  • NSPredicates
  • Relationships

ViewContext
It is an anchor to communicate with database

    

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {

            return nil

        }


    let context = appDelegate.persistentContainer.viewContext





NSManagedObject
This is special kind of objects to be stored in core data database.

    

    ManagedObjectName(entity: Entity, insertInto: Context)





NSEntity
You can refer this as a table in SQL, we can add multiple entities in core data and can add column with its type to entity.


    NSEntityDescription.entity(forEntityName: EntityName, in: Context)





NSFetchRequest
We need to create a fact request to fetch data from core database. We can add predicate to filter the data to this request.

    

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityName)


    fetchRequest.predicate = NSPredicate(format: "%K = %@", ColumnName, Value as CVarArg)


    do {

         let results = try Context.fetch(fetchRequest)

    } catch let error as NSError {

         print(error)

    }





Save data

    

    do {

            try Context.save()

        } catch let error as NSError {

            print(error)

        }





Update data
Use fetch to fetch the designed object to update. Once you get the object then modify its properties and call save()



Relationship Rules
There are two types of relationship, One to One , One to Many
Refer the below diagram to understand the rules of relationship.










More links









Comments

Popular posts from this blog

SubString in Swift

PUSH Notification