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, High school drop-out. College drop-out. A go-go dancer in Amsterdam. LOVED computers, programmed satellites for AT&T. Founded IPSOFACTO in 1996, Y2K boom, Dot-Com boom, 2.0 boom. Likes his smallish company and human relationships; not into big anonymous IT. Loves to tell jokes. Loves and Hates technology; pick up the phone, ok? Thinks on line hook up sites have saved the world from AIDS and DateRape. Thinks his kids are better collaborators and world leaders thanks to video games. Is still a hip-hop dancer; is NOT a Brony. Loves San Francisco; Hates the homeless crisis. Tells young people to buy real estate, as soon as possible. Don’t rent. Hopes his final years are spent handing out blankets, food, clothes, and medical supplies.