Channels ▼


Understanding Core Data on iOS

To create an instance, use the factory method initWithManagedObjectModel:. Make sure to precede the method call with a call to alloc().

NSPersistentStoreCoordinator *tFoo;
NSManagedObject *tBar;
tFoo = [[NSPersistentStoreCoordinator alloc] 

For input, pass an instance of NSManagedObject (more about this later). The method returns a valid instance if successful; otherwise, it returns a nil.

Once you have a valid instance, use the instance method addPersistentStoreWithType:… to prepare the coordinator. This method takes five arguments. The first argument sets the store type. For a SQLite database, this would be the constant NSSQLiteStoreType. The second argument configures the database. For a default configuration, pass a nil for this argument. The third argument is the location of the database file. The fourth defines the store options. If there are no options, pass a nil as input. The last argument is an error object, made with an NSError class.

NSPersistentStore *tSrc; 
NSURL *tPth; 
NSError *tErr; 
tPth = [NSURL fileURLWithPath:@"/Users/Foo/Foo.sqlite"]; 
tSrc = [tFoo addPersistentStoreWithType:NSSQLiteStoreType 
	configuration:nil  URL:tPth 
	options:nil  error:&tErr]; 

The method returns an instance of NSPersistentStore when successful. Otherwise, it returns a nil. If the database file does not exist, the method will create a new empty file. To remove an existing persistent store, use the method removePersistentStore:error:. Pass along an NSPersistentStore instance and an error object for input. The method returns a YES when removal was successful. Make sure there are no pending changes before removing a specific store.

For a list of active persistent stores, use the method persistentStores. This returns an array object, with each element an instance of NSPersistentStore. For a specific store, use persistentStoreForURL:. Pass the path to a database file as an NSURL object. The method returns the persistent store handling the given file. Conversely, use URLForPersistentStore: to locate the database file associated with a specific store. Pass the NSPersistentStore instance created for that file.

The NSManagedObjectModel (Figure 4) holds the schema describing a database. To create an instance, use the method initWithContentsOfURL: and pass for input the path to the schema resource file.

NSURL *tPth;
NSManagedObjectModel *tBar;
tPth = [NSURL fileURLWithPath:@"/Library/Application Support/Foo/Bar.momd"]; 
tBar = [[NSManagedObjectModel alloc] 	initWithContentsOfURL:tPth]; 

Figure 4: NSManagedObjectModel holds the schema describing a database.

The method returns a valid instance when successful; otherwise, it returns a nil. Next, pass the object to the NSPersistentStoreCoordinator instance as described earlier. The NSManagedObjectContext class (Figure 5) wraps a mutable layer around an NSManagedObjectModel instance. Together, these two classes form the managed object context for the database.

Figure 5: The NSManagedObjectContext class, whichwraps a mutable layer around an NSManagedObjectModel instance.

Use a standard alloc/init to create an instance of NSManagedObjectContext. Then use setPersistentStoreCoordinator: to link the instance to a coordinator object.

NSManagedObjectContext *tDB;
tDB = [[NSManagedObjectContext alloc] init];
[tDB   setPersistentStoreCoordinator:tFoo];

The class also has three sets of methods for performing and managing a record transaction. The first set adds new records to the database or marks existing records for deletion. The second provides access to the queue buffers. The third set commits the queued changes or disposes of them altogether.

The NSEntityDescription class (Figure 6) describes each table in the database. It provides access to a table's record structure, and it reserves space for a new record.

For instance, to retrieve the table name, use the name accessor. For a list of record fields, use the properties accessor. For fields that hold only values, use attributesByName. For fields that hold only relations, use relationshipsByName.

Figure 6: The NSEntityDescription class describes each table in the database.

Finally, to start a new record, use the factory method insertNewObjectForEntityForName:inManagedObjectContext:. This method takes two arguments: the table entity's name and the database context.

NSManagedObject *tRec;
tRec = [NSEntityDescription 

Figure 7: The NSManagedObject class.

To create a new record, use the method initWithEntity:insertIntoManagedObjectContext:.

NSManagedObject *tRec;
NSEntityDescription *tTbl;
tRec = [[NSManagedObject alloc] initWithEntity:tTbl

For input, pass the table's NSEntityDescription object and the database's NSManagedObjectContext object. This method also returns a valid instance or a nil depending on success. Notice it does the same task as the factory method from NSEntityDescription.

To identify the record's table entity, use the entity accessor. To identify its database, use the managedContext accessor. To find out if the record is a new one, use isInserted. To find out if it has changed or is queued for deletion, use isUpdated or isDeleted.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.