Apress Access

Pro Core Data for iOS, Second Edition

2nd Edition

By Michael Privat , Robert Warner

  • eBook Price: $31.99
Buy eBook Buy Print Book
Pro Core Data for iOS explains how to use the Core Data framework for iOS SDK 5 using Xcode 4.2. The book explains both how and why to use Core Data, from simple to advanced techniques.

Full Description

  • Add to Wishlist
  • ISBN13: 978-1-4302-3656-6
  • 400 Pages
  • User Level: Intermediate to Advanced
  • Publication Date: November 29, 2011
  • Available eBook Formats: EPUB, MOBI, PDF

Related Titles

  • Beginning Xcode: Swift 3 Edition
  • Practical Swift
  • Migrating to Swift from Flash and ActionScript
  • Agile Swift
Full Description

Fully updated for Xcode 4.2, Pro Core Data for iOS explains how to use the Core Data framework for iOS SDK 5 using Xcode 4.2. The book explains both how and why to use Core Data, from simple to advanced techniques. Covering common and advanced persistence patterns, this book prepares any iOS developer to store and retrieve data accurately and efficiently.

This book starts by giving you a solid grounding in Core Data, providing a foundation for the rest of the book. With this knowledge, you'll have all you need to master Core Data and power your data-driven applications. You'll see how to work with SQLite and how to create an efficient data model to represent your data. Once you've established your data model, you'll learn how to work with data objects and refine result sets to get the most out of the stored data.

The advanced portions of the book begin by showing you how to tune your apps' performance and memory usage, to give you a truly professional edge. You'll see how to version and migrate your data as well, to ensure your data stays organized and efficient. Finally, the book covers managing table views with NSFetchedResultsController.

What you’ll learn

  • Core Data techniques with Xcode
  • How to organize data appropriately
  • How to persist data efficiently
  • How to effectively use Apple tools
  • How to build Core Data applications
  • How to use Core Data in advanced settings
  • How to version and migrate data as your applications evolve
  • How to tune and optimize persistence

Who this book is for

All iPhone, iPad, and iPod touch developers whose applications manage any amount of data.

Table of Contents

Table of Contents

  1. Getting Started
  2. Understanding Core Data
  3. Storing Data: SQLite and Other Options
  4. Creating a Data Model
  5. Working with Data Objects
  6. Refining Result Sets
  7. Tuning Performance and Memory Usage
  8. Versioning and Migrating Data
  9. Managing Table Views Using NSFetchedResultsController
  10. Using Core Data in Advanced Applications
Source Code/Downloads

Downloads are available to accompany this book.

Your operating system can likely extract zipped downloads automatically, but you may require software such as WinZip for PC, or StuffIt on a Mac.


If you think that you've found an error in this book, please let us know by emailing to editorial@apress.com . You will find any confirmed erratum below, so you can check if your concern has already been addressed.

On page Chapter 5:

One needs to have the source code to BOTH examples for this chapter. I can't get the first one to draw the shapes. I get the following error:

CGContextAddLineToPoint: no current point.

On page 5:
Please see below for Errata submitted by author Rob Warner.

Author Comment:
The instructions for creating the BasicApplication project should include:

* Enter BasicApplication for Class Prefix

* Check the box for Use Automatic Reference Counting

Figure 1-2 should include a field for Class Prefix with the text BasicApplication.

Figure 1-2 should include a checkbox for Use Automatic Reference Counting, which should be checked.

The generated code names for the BasicApplication project should now have the BasicApplication prefix on them. References to MasterViewController (and its .h and .m files), for example, should now point to BasicApplicationMasterViewController.

On page 9:

See below for Errata submitted by author Rob Warner.
Author Comment:

The class diagram in Figure 1-6 should show the class BasicApplicationMasterViewController in place of MasterViewController.

The generated code for BasicApplicationMasterViewController's initWithNibName:bundle: method now differs from the listed code, and does not address the setting of the Managed Object Context. The Managed Object Context is now set in the BasicApplicationAppDelegate class, in the application:didFinishLaunchingWithOptions: method, in the line:

masterViewController.managedObjectContext = self.managedObjectContext;

On page 10:

Please see below for Errata submitted by author Rob Warner:
Author Comment:

The screenshot in Figure 1-7 should reflect the filenames with the "BasicApplication" prefix, e.g. BasicApplicationMasterViewController.h

On page 22-23:

The code gives compiler warnings because its not ARC compatible.

Here is ARC compatible code:

Add #import <CoreData/CoreData.h> before @class
Add following code between last @property line and @end:
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

Add following code after last @synthesize line:
@synthesize managedObjectModel = __managedObjectModel;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

Add following code between last method and @end:
- (void)saveContext
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
if (__managedObjectContext != nil) {
return __managedObjectContext;

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
return __managedObjectContext;

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
if (__managedObjectModel != nil) {
return __managedObjectModel;
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JSONtester" withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JSONtester.sqlite"];

NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
Replace this implementation with code to handle the error appropriately.

abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.

If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

return __persistentStoreCoordinator;

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

Add following code within (void)applicationWillTerminate and (void)applicationDidEnterBackground methods:
[self saveContext];

Rest of example code should work fine.

On page 68:

On figure 3-10, delete rule should be Cascade instead of Nullify.

On page 263-277:

Chapter 8 Migration using mapping model

I've tried multiple times with the source code provided and each time produces this error when migrating with the mapping model:

Unresolved error Error Domain=NSCocoaErrorDomain Code=134140

reason=Can't find mapping model for migration}

full console output: http://pastebin.com/pUiYAN9E

Using Xcode 4.2.1

On page 296 - 304:

I'm concerned about something that you have in "RESPONDING TO DATA CHANGES".

You're pulling out the "configureCell" method to allow it to be called from the FetchedResultsControllerDelegate, but your implementation on page 304 SEEMS to be causing configureCell to be called TWICE. It's called ONCE during the outer [self configureCell:atIndexPath:] call that then calls cellForRowAtIndexPath: which calls configureCell AGAIN.

Granted, it's not a HUGE performance hit, but it seems an odd thing to be holding up as a best practice in a book trying to show folks that are potentially new to CoreData how to use it.

Am I missing something? Thanks in advance for any advice.


    1. Swift Game Programming for Absolute Beginners


      View Book

    2. iPhone and iPad Apps for Absolute Beginners


      View Book

    3. Learn iOS 8 App Development


      View Book

    4. Swift Recipes


      View Book