- Core Data iOS Essentials
- B.M.Harwani
- 1209字
- 2025-02-25 21:03:07
Core Data API
The Core Data API, also called the stack, consists of three main components:
NSPersistentStoreCoordinator
NSManagedObjectModel
NSManagedObjectContext
The PersistentStoreCoordinator
plays a major role in storing and retrieving managed objects from the Persistent Store via ManagedObjectContext
. We can see in the following figure how the three are related:

The Managed Object Model (an instance of NSManagedObjectModel
class) is created from the data model of our application. If there is more than one data model in our application, the Managed Object Model is created by merging all of the data models found in the application bundle. The managed object (instance of the NSManagedObject
class or its subclass) represents an instance of an entity that is maintained (managed) by the Core Data framework. A managed object is an instance of an Objective-C class, but it differs from other objects in three main ways:
For working with a managed object, it is loaded into memory. The managed object context maintains the state of the managed object after it is loaded in memory. The Managed Object Context tracks in-memory changes that have yet to be persisted to the data store. Any changes made to the state of an NSManagedObject
do actually affect the state of the object in memory, not just the persistent representation of that object in the data store. When we want to commit the modifications made to the managed object, we save the managed object context to the persistent store. In order to deal with persistent store, the managed object context needs a reference to a PersistentStoreCoordinator
. In other words, a pointer to the PersistentStoreCoordinator
is required for creating a Managed Object Context. Remember, the PersistentStoreCoordinator
is the essential middle layer in the stack that helps in storing and retrieving the managed object model from the persistent store.
Note
The managed object context is an object that plays a major role in the life cycle of managed objects. It handles all the aspects of managed object from faulting to validation including undo/redo. To modify managed objects, they are fetched from a persistent store through managed context. The modified managed objects are committed to the persistent store through context only. The managed objects represent data held in a persistent store. Faulting is considered to occur for an object whose property values have not yet been loaded from the external data store.
To access the objects (entity) in managed object context, FetchRequest
, an instance of NSFetchRequest
class, is used. To define the entity to be retrieved via NSFetchRequest
, we pass the appropriate NSEntityDescription
to the NSFetchRequest
.
The result, that is, the set of entities retrieved from the managed object context (on the basis of FetchRequest)
are managed by FetchedResultsController—an
instance of NSFetchedResultsController
.
In fact, FetchRequest
is passed to the FetchedResultsController
along with a reference to the managed object context. Once the NSFetchedResultsController
class has been initialized, we can perform a fetch operation to load the entities (stored in it) into memory.
Note
The managed object context keeps track of all the changes made to the managed object since the last time it was loaded in memory and hence helps in undoing any changes made to the managed object (if required).The Persistent Store Coordinator helps in avoiding redundancy if multiple calls are made by different classes on the same file at the same time, that is, the multiple calls are serialized by the NSPersistentStoreCoordinator
class to avoid redundancy.
Let us now get a detailed understanding of the terms used above.
Persistent Store
Persistent Store is a data store (repository) that handles mapping between data (in the store) and corresponding objects in a managed object context. The managed contexts can be stored in any of the following three formats—In-memory, Binary, and SQLite database format. In other words, the Persistence Store can be of three types—In-memory store, Binary store, and SQLite store.
- The In-memory store is used in caching mechanism
- Binary format stores information in a non-human-readable form but provides better performance
- SQLite database format is scalable and is the fastest
The drawback with the Binary and In-memory store contents is that they have to be entirely loaded in memory at startup and hence consume a lot of memory, whereas the SQLite store can be loaded and unloaded from memory as per requirements. SQLite is an open source embedded database that is highly preferred for Core Data.
Note
A persistent store is associated with a single data model.
Persistent Store Coordinator
The Persistent Store Coordinator is an instance of the NSPersistentSoreCoordinator
class that performs co-ordination between managed object contexts and persistent store, that is, it helps in storing and retrieving the managed object model from the Persistent Store. All the calls that require "reads" or "writes" to the Persistent Store are serialized by the Persistent Store Coordinator (so that multiple calls against the same file are not being made at the same time). The Persistent Store Coordinator creates a path to a file (on disk drive) in the Documents
directory in our application's sandbox.
FetchRequest
FetchRequest
is an instance of the NSFetchRequest
class and is used to access the objects in managed object context. There are two parts to the creation of an NSFetchRequest:
- Deciding the entity to be retrieved
- Defining an
NSPredicate
to define the criteria (condition) to retrieve only the desired objects (this part is optional)
To define the entity to be retrieved via NSFetchRequest
, we pass the appropriate NSEntityDescription
to the NSFetchRequest
. Recall that NSEntityDescription
consists of the name of the entity, its attributes, relationships, and so on.
When NSFetchRequest
is executed against the NSManagedObjectContext
, the result may be either in the form of an NSArray
(containing the fetched entities) or there may be an error. That is why, the execution of an NSFetchRequest
accepts a pointer to an NSError
to describe the errors that may occur while execution. If the execution of NSFetchRequest
fails, then the pointer will be directed to an instance of NSError
that contains the reason of failure. The method signature will be as follows:
NSError *error; NSArray *myArray = [myManagedObjectContext executeFetchRequest: fetchRequest error:&error]
FetchedResultsController
FetchedResultsController
is an instance of the NSFetchedResultsController
class and as the name suggests, the NSFetchedResultsController
class is meant for managing the result—the set of entities from an NSManagedObjectContext
that are retrieved on the basis of FetchRequest
. It helps with the following:
- Querying the retrieved result
- Arranging the result
- Notifying
UIViewController
in case any of the entities in the result set are modified (added, deleted, updated, and so on)
The NSFetchedResultsController
requires an NSFetchRequest
for its initialization. The NSFetchRequest
contains the criteria of the entities that are accessed through the NSFetchedResultsController
. The NSFetchRequest
is passed to the NSFetchedResultsController
along with a reference to the NSManagedObjectContext
. Once the NSFetchedResultsController
has been initialized, we can perform a fetch operation to load the entities into memory.
We have enough knowledge of Core Data and its different components. Let us see what kind of application we will be developing in this book using Core Data.