Upgrade to Pro — share decks privately, control downloads, hide ads and more …

UIManagedDocument with Core Data by Alondo Brew...

UIManagedDocument with Core Data by Alondo Brewington

Alondo discusses using UIManagedDocument with Core Data at CocoaHeads Raleigh in April 2012

Triangle Cocoa

July 01, 2012
Tweet

More Decks by Triangle Cocoa

Other Decks in Programming

Transcript

  1. Asynchronous I/O Snapshots taken for open/read /save work happens on

    a background queue Completion handler block executed on main queue
  2. Data Load // Create UIManagedDocument with URL UIManagedDocument *myAppDatabase =

    [[UIManagedDocument alloc] initWithFileURL:myAppDBFileURL]; NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; myAppDatabase = options; [myAppDatabase saveToURL:myAppDBFileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){ if (!success) { // Handle the error. }else { // Perform functions for created database (e.g. insert default data) } }];
  3. Saving - (void)performUpdate { NSManagedObjectContext *context = myAppDatabase.managedObjectContext; NSSet *inserts

    = [context insertedObjects]; if ([inserts count]) { NSLog(@"Inserting %d new objects", [inserts count]); NSError * error = nil; if ([context obtainPermanentIDsForObjects:[inserts allObjects] error:&error] == NO) { NSLog(@"[DataManager performUpdate]! %@", error); } } [myAppDatabase updateChangeCount:UIDocumentChangeDone]; }
  4. Migration // If legacy store exists, copy it to the

    new location NSURL *legacyPersistentStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"OldDatabase.sqlite"]; NSFileManager* fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:legacyPersistentStoreURL.path]) { NSLog(@"Old db exists"); NSError* thisError = nil; [fileManager replaceItemAtURL:storeURL withItemAtURL:legacyPersistentStoreURL backupItemName:nil options:NSFileManagerItemReplacementUsingNewMetadataOnly resultingItemURL:nil error:&thisError]; NSLog([thisError localizedDescription]); } return [super configurePersistentStoreCoordinatorForURL:storeURL ofType:fileType
  5. Resources WWDC 2011: Session 303 - What’s New in Core

    Data on iOS WWDC 2011: Storing Documents in iCloud using iOS 5 iTunes: Stanford - iPad and iPhone Application Development