01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

252 CHAPTER 12 Reading and writing application data<br />

optional), Core Data does most of the work for you. Such migrations are called lightweight<br />

migrations. Let’s see what this looks like in practice: you’ll add a new property—<br />

age—to the Person entity. To do that, you must first create a new version of your data<br />

model. Select the PocketTasks.xcodedatamodel, then select Editor > Add Model Version<br />

from the menu. A new file called PocketTasks 2.xcdatamodel will appear in the<br />

PocketTasks.xcdatamodeld directory. This new version should be used by your application<br />

from now on. For that to take effect, select PocketTasks.xcdatamodeld and<br />

choose “PocketTasks 2” from the “Current” select box in the “Versioned Data Model”<br />

section of the first tab of the Utilities pane. The file will get a little green checkmark.<br />

Now add the new age property to the Person entity in the new version you just created.<br />

Make it optional, and set the type to Integer16. Save it and build and run. The<br />

application will crash and report errors in the Console: the saved data is incompatible<br />

with the new data model! You have to tell Core Data to automatically migrate it for<br />

you. Open PocketTasksAppDelegate.m and find the persistentStoreCoordinator<br />

method. Change it to look like the following listing.<br />

Listing 12.17<br />

Automatically migrate a data model in PocketTasksAppDelegate.m<br />

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {<br />

if (__ persistentStoreCoordinator != nil) {<br />

return __persistentStoreCoordinator;<br />

}<br />

NSURL *storeURL =<br />

[[self applicationDocumentsDirectory]<br />

URLByAppendingPathComponent:@"PocketTasks.sqlite"];<br />

NSDictionary *options =<br />

[NSDictionary dictionaryWithObjectsAndKeys:<br />

[NSNumber numberWithBool:YES],<br />

NSMigratePersistentStoresAutomaticallyOption,<br />

[NSNumber numberWithBool:YES],<br />

NSInferMappingModelAutomaticallyOption, nil];<br />

NSError *error = nil;<br />

__persistentStoreCoordinator =<br />

[[NSPersistentStoreCoordinator alloc]<br />

initWithManagedObjectModel:[self managedObjectModel]];<br />

if (![__persistentStoreCoordinator<br />

addPersistentStoreWithType:NSSQLiteStoreType<br />

configuration:nil<br />

URL:storeURL<br />

options:options<br />

error:&error])<br />

{<br />

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);<br />

abort();<br />

}<br />

}<br />

return __persistentStoreCoordinator;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!