Introduction to Core Data
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.
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.
The model you create is then saved in a file with the extension .xcdatamodel.
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.
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];
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!