Introduction to Core Data
Introduction
CoreData is a framework to work with databases and persistence on iPhone/iPad/Mac.
It’s similar to an ORM–your data will be managed in memory through a graph of objects.
Then, you can request CoreData to serialize this data to a file.
Model
CoreData uses a model which describes how your data should be written on the disk.
Fortunately, Xcode has a great tool to create models: Right click on your project and Add…, New File, under Resource choose Mapping Model.
Each entity require a type, by default NSManagedObject is used. You can also change the type of your entities from NSManagedObject to a class of your choice.
The model you create is then saved in a file with the extension .xcdatamodel.
Core Data
To interact with your model, three steps are required:
- Load your model to memory
- Init the layer to write and read your data from the disk
- Init the context to interact with your data (query, search, etc…)
The first step is to load your model in a NSManagedObjectModel–for that you have to use a URL to your .xcdatafile.
NSManagedObjectModel* managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:URLToMyModel];
The NSPersistentStoreCoordinator is the layer that will allow your context to interact with your data on the disk, you can compare that to a driver.
coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
The last step is to create your context :
NSManagedObjectContext* context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:coordinator];
Some relationships disapear when I save and then restore my data.
Don’t forget that CoreData will use your model to write your data to the disk!
