Introduction to Core Data

Introduction to Core Data

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.

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:

  1. Load your model to memory
  2. Init the layer to write and read your data from the disk
  3. 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!

For instance, if you set a relationship as 1-n in your model but use it as a n-n in your code, superfluous relationships will not be written (and CoreData will say nothing about that !).

Steve Boullianne, Multiple post-graduate degrees, Mind/Body/Spirit enthusiast, & a member of Mensa. Loves Skiing, Scuba, and Food. Steve’s First job out of college was programming satellites for AT&T. Founded IPSOFACTO in 1996, Y2K boom, e-Commerce super success, 2.1 boom. Steve is ready to Mediate high quality for all life, our one planet, and human kindness. Loves to dance and tell jokes. Steve believes that Excellent Communication is key to human success (and failure). Steve has 3 sons who are his STARS. They will carry the world into a brilliant future. Since 1996, Steve has been a volunteer drug and alcoholism counselor in the Bay Area. The power of the Great Spirit is in you. Steve is a good friend to have.