Core Data part 1 and 2 – data model and data stack

DEMO PROJECT

Create a Single Project

name it “CoreDataTut”

We’re going to do everything by scratch so do not check the Core Data box. Leave it blank.

Generate a xcdatamodeld file

Once the project is generated, look at your list view on the left side. We need a .xcdatamodeld file, which represents the model diagram of our entities. The reason why is because core data code need to use a .xcdatamodeld to initialize a Managed object Model, which it uses to save state and data.


See how to create a data model here

In our core data stack, we actually load this file into an NSManagedObjectModel object.
Make sure that the name of your data model . xcdatamodeld file matches that of the name you use in your code. We do this by using global #define as noted in the code below.

The core data stack

First we make a singleton object out of Core data’s basics by creating a singleton class that houses

  • NSManagedObjectContext
  • NSManagedObjectModel
  • NSPersistentStoreCoordinator

From a picture perspective, core data’s basic parts are connected like this:

basic_core_data_diagram

Create the source file:

coredata_create_corestack

Click on Cocoa Touch Class, and input “THCoreDataStack”. The subclass should be “NSObject”.

coredata_name_corestack

THCoreDataStack.h source

THCoreDataStack.m

Managed Object Model

The lazy loading and getter method of our MOM.

http://stackoverflow.com/questions/10579767/why-the-extension-is-momd-but-not-xcdatamodel-when-search-the-path-for-the-m

The mom and momd files are compiled versions of xcdatamodel and xcdatamodeld files…so here we’re just saying that we need to allocate a NSManagedObjectModel object and init with the compiled versions of our xcdatamodeld files.

Basic lazy loading of the PSC, and its getter. When creating the PSC, we use a #define macro for the sql’s file name.

Managed Object Context – scratch pad for DB changes

This MOC is basically a scratch pad for database changes. Later, when you save context, it will be reflected to the Persistent Store Coordinator, and thus, the database.
We have basic lazy loading and get methods for the MOC.

Saving the Context

This method is called right after an Object is returned from the MOC designated to be inserted or changed.

That way the MOC’s changes are safely saved.