Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

Embedded Systems

Understanding Core Data on iOS

Next, initInjury creates a new NSManagedObject instance for each injury term (lines 20-22). It updates each record field using setValue:forKey: (lines 26-32), and it queues the record for insertion using insertObject: (line 35). The records stay queued until dbContext gets a save: message (see Listing One).

We can use the same code to prepare the constant table Status. All we have to change is the sequence string (@"Morgue%Immediate%Delayed%Minor") and the table name. Listing Three shows how to add a new record to the Person table. Again, the code creates an instance of NSManagedObject (lines 12-14). It hashes the person's name (line 18) to produce the record's primary key. The code then updates each record field using setValue:forKey: (lines 21-26). And it queues the record for insertion by passing it to insertObject: (line 31).

NSString *tNom;
NSInteger tAge, tUID;
BOOL tMan;
NSManagedObject *tRec;

// the test patient
tNom = @"John Doe";
tAge = 49;
tMan = YES;

// create a new record
tRec = [NSEntityDescription 
if (tRec != nil)
	// generate the primary key
	tUID = [tNom hash];
	// prepare the record
	[tRec setValue:[NSNumber numberWithInteger:tUID]
	[tRec setValue:tNom forKey:@"name"];
	[tRec setValue:[NSNumber numberWithInteger:tAge]
	[tRec setValue:tMan forKey:@"male"];
	// ... updating the Vitals table
	// insert the record
	[dbContext insertObject:tRec];
	// ...commit the record to make it available
Listing Three.

Now, we can use the same code to add a record to the Vitals table. All that needs to change are the record fields and the target table. We can even use the same uid value for the record's primary key. But how do we relate a Vitals record with the Person record? To do so, use the setValue:forKey: method as shown here:

NSManagedObject *tRec, tVit;
// ... create the Person and Vitals records
[tRec  setValue:tVit forKey:@"vitals"];

When we commit the record, Core Data will set the vitals field on the Person record to the Vitals record's key.

Listing Four shows how to do a simple record query. This sample code targets the Injury table and retrieves the record "Burn." It starts by creating an instance of NSEntityDescription (lines 14-15). Then it creates an instance of NSFetchRequest and sets the target table and result type (lines 18-20).

NSManagedObject *tInj;
NSEntityDescription *tTbl;
NSFetchRequest *tQry;
NSPredicate *tCon;
NSInteger tKey;

NSError *tErr;
NSArray *tLst;

// set the secondary key
tKey = 1 'choosing "Burn" as the injury

// set the query target
tTbl = [NSEntityDescription entityForName:@"Injury" 
// initialise the query object
tQry = [[NSFetchRequest alloc] init];
[tQry setEntity:tTbl];
[tQry setResultType:NSManagedObjectResultType];

// set the query condition
tCon = [NSPredicate predicateWithFormat:@"(id=%@)"
		, [NSNumber numberWithInt:tKey]];
[tQry setPredicate:tCon];

// perform the query
tLst = [dbContext executeFetchRequest:tQry 
[tQry release];

// retrieve the query result
if ((tLst != nil) 
	&& ([tLst isKindOfClass:[NSObject class]]))
	tInj = [tLst objectAtIndex:0];
Listing Four.

Next, the query code makes an instance of NSPredicate (lines 23-25). Here, it uses a C-style format string to prepare the query condition. The code passes the predicate condition to the NSFetchRequest instance via the setPredicate: method.

Finally, the code performs the query using the method executeFetchRequest:error: (lines 28-29). For input it passes the NSFetchRequest instance and an NSError object. The method returns an NSArray object when it succeeds, a nil when it failed. The query code disposes of the query with a release message (line 30). Then it reads the first element from the array (line 35). Note the code did not use a single SELECT command.

What if we want the query to retrieve all existing records? Just do not create an instance of NSPredicate. Or pass a nil to the setPredicate: method.

Suppose we want to remove an existing record. First, query for the record as described in Listing Four. Then use the deleteObject: method to mark the record for deletion.

NSManagedObject *tRec;
// ... perform a record query
[dbContext  deleteObject:tRec];
The record is then queued for deletion. To commit the deletion, use the NSManagedObjectContext method save: as shown in Listing One (line 114). To undo the last deletion, use the undo method:
  [dbContext undo];

Concluding Remarks

Core Data provides the means to create and manage databases from an iOS application. In this article, I examined the key classes of the Core Data framework and explained how these classes work with a database. And I looked at how to define a database schema using the new schema editor in Xcode. Future articles will discuss other data-oriented classes in iOS.


Core Data Programming Guide. MacOS X Developer Library [PDF] .

Core Data Framework Reference. MacOS X Developer Library [PDF].

Core Data Tutorial for iOS. iOS Developer Library. [PDF].

José Cruz is a freelance engineering writer based in British Columbia and a frequent contributor to Dr. Dobb’s.

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.