Rinat Khanov
Rinat Khanov

Reputation: 1576

Core Data: handle the case when iCloud turns off / on

I am implementing iCloud support in my Core Data app (iOS 7 only, not released yet, iCloud support will be from Day I). I've checked out WWDC 2013 207 session about changes in iCloud and I am really glad to see the improvements (I had some previous experience with iCloud too).

Things are working really great. However, I am not sure how to handle the case when user enables or disables iCloud from system preferences — this results to creating new .sqlite files in another directory and therefore user data loss.

Here's how I implement persistent store adding:

- (void) addPersistentStoreToCoordinator {

    NSMutableDictionary *options = [NSMutableDictionary dictionary];
    [options setObject:@YES forKey:NSMigratePersistentStoresAutomaticallyOption];
    [options setObject:@YES forKey:NSInferMappingModelAutomaticallyOption];

    NSURL *iCloud = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier: nil];

    if (iCloud) {
         [options setObject:@"ABC123~com~myapp~myapp" forKey:NSPersistentStoreUbiquitousContentNameKey];
    }

    NSError* error;

// the only difference in this call that makes the store an iCloud enabled store
// is the NSPersistentStoreUbiquitousContentNameKey in options.

    [persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType
                                          configuration:nil
                                                    URL:self.storeURL
                                                options:options
                                                  error:&error];
}

- (NSURL *)storeURL {

    NSURL *documentsDirectory = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                                       inDomain:NSUserDomainMask
                                                              appropriateForURL:nil
                                                                         create:YES
                                                                          error:NULL];

    return [documentsDirectory URLByAppendingPathComponent:@"MyApp.sqlite"];
}

How do I save data from Core Data when user switches off/on iCloud preference in the settings?

(Side note: I've managed to manually handle the case when iCloud goes from state [OFF] > [ON] — fetching all data from old Core Data, then saving these NSManagedObject subclasses to newly created Core Data with iCloud enabled. However, this code is very app-specific (and pretty unstable). I am looking for more generic solutions).

Thanks

Upvotes: 4

Views: 939

Answers (1)

Wyatt Page
Wyatt Page

Reputation: 309

I had the exact same questions and found this https://gist.github.com/mluisbrown/7015953 . Works perfectly for me now.

Upvotes: 1

Related Questions