Core Data in Swift
- Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems.
- It allows data organized by the relational entity–attribute model to be serialized into XML, binary, or SQLite stores.
How Core Data is diffrent from SQLite
Core Data Limitations
important limitation is the threading model of Core Data. The framework expects to be run on a single thread. Fortunately, Core Data has evolved dramatically over the years and the framework has put various solutions in place to make working with Core Data in a multithreaded environment safer and easier.
Core Data Stack
The Core Data stack is a collection of framework objects that are accessed as part of the initialization of Core Data and that mediate between the objects in your application and external data stores.
A Core Data stack is composed of the following objects → one or more managed object contexts connected to a single persistent store coordinator which is in turn connected to one or more persistent stores.
1. Managed Object Context (MOC)
Its primary responsibility is to manage a collection of Managed Objects (Entities). A Managed Object Context maintains the state of entities, typically in memory.
Application can create one or more MOC per stack. Context is connected to persistent store coordinator or from parent context
It provides Caching, Change tracking, Lazy loading, Redo, Undo and validation features
2. Persistent Store Coordinator (PSC)
Instance of NSPersistentStoreCoordinator. The coordinator is the central object in a Core Data stack.
The persistent store coordinator role is to manage multiple/single stores and present to its managed object contexts the facade of a single unified store as shown below in the figure coordinator communicating to multiple stores.
It has a reference to a managed object model as shown below in the figure. Persistent store coordinator can talk or have a reference of the majority of the components in a stack
3. Persistent store
You can think of a persistent store as a database file (Sqlite) where individual records each hold the last-saved values of a managed object (Entity).
We can make multiple persistent stores per stack
Core Data offers three native file types for a persistent store: binary, XML, and SQLite. You can implement your own store type if you want Core Data to interoperate with a custom file format or server.
4. Managed object model
A managed object model is a set of objects that together form a blueprint describing the managed objects you use in your application
Schema of the model objects you use in your application
Process to Add Records in Core Data
The process of adding the records to Core Data has following tasks
- Refer to persistentContainer from appdelegate
- Create the context from persistentContainer
- Create an entity with User
- Create new record with this User Entity
- Set values for the records for each key
Process to Retrieve Data from Core Data
The process of fetching the saved data is very easy as well. It has the following task
- Prepare the request of type NSFetchRequest for the entity (User in our example)
- if required use predicate for filter data
- Fetch the result from context in the form of array of [NSManagedObject]
- Iterate through an array to get value for the specific key
We can fetch the data from our Users entity using following code.
Process to Update Data in Core Data
For update record first we have to fetch/Retrieve data with predicate as same as above Retrieve data process. Then below few steps to follow
- Prepare the request with predicate for the entity (User in our example)
- Fetch record and Set New value with key
- And Last Save context same as create data.
Process to Delete record in Core Data
For delete record first we have to find object which we want to delete by fetchRequest. then follow below few steps for delete record
- Prepare the request with predicate for the entity (User in our example)
- Fetch record and which we want to delete
- And make context.delete(object) call (ref image attached below)
Delete Rules of Core Data Relationships
Core data supports four basic delete rules:-
1. No Action
2. Nullify
3. Cascade
4. Deny
1. No Action Delete Rule
If the delete rule is set to No Action to the relationship, then nothing happens. Let’s take an example, if department has many employees, If the department is deleted, Nothing happens to an employee. Employee assumes that it’s still associated with deleted department.
2. Nullify Delete Rule
If the delete rule is set to Nullify to the relationship, then the destination of the relationship gets nullify. In our case, If the department has many employees and department is deleted, the relationship between department and employee gets nullify.
This is default delete rule and we often use this rule in our project.
3. Cascade Delete Rule
This delete rule is important and makes sure for all possible scenarios while setting this rule to the relationship. This rule is mostly used when data model has more dependency. Means in our case, if department has many employees and if department is deleted, automatically all employee belonging to that department are deleted.
Before using this rule, please make sure your project requirement. Because this rule will delete all your records without any intimation if your relationship object is deleted.
4. Deny Delete Rule
This rule is powerful and simply opposite to the cascade rule. Instead of deletion of all your records in cascade rule, it prevents the deletion of records.
In our case, if department has many employees, department is only deleted if all employee belonging to same department are deleted or no employee is tied with the same department.
This is all about delete rules of core data. Please understand this concept before you deal with relationship between two entities. Also Understand your requirement before setting delete rule.
************* Thanks for reading…….. Randhir Raj *************