Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magical Record and iCloud enabling/disabling

How to handle correct the following flow using Magical Record? Assume that my app enable feature to switch iCloud sync on/off.

  1. The user installs the app. On startup he is asked about iCloud preference. His choice: do not use iCloud.
  2. The user creates some data in the app. Then he decides to store it in iCloud and enables iCloud.
  3. Later by some reason the user disables iCloud in the app. Data should be left locally.

How to setup Magical Record correctly?

UPDATE:

Source code

like image 200
orkenstein Avatar asked Oct 01 '22 07:10

orkenstein


1 Answers

Implementing a switch to enable or disable iCloud in your app is also much easier in iOS 7, although it probably isn’t necessary for most applications. Because the API now automatically creates a separate file structure when iCloud options are passed to the NSPersistentStore upon creation, we can have the same store URL and many of the same options between both local and iCloud stores. This means that switching from an iCloud store to a local store can be done by migrating the iCloud persistent store to the same URL with the same options, plus the NSPersistentStoreRemoveUbiquitousMetadataOption. This option will disassociate the ubiquitous metadata from the store, and is specifically designed for these kinds of migration or copying scenarios. Here’s a sample:

- (void)migrateiCloudStoreToLocalStore {
    // assuming you only have one store.
    NSPersistentStore *store = [[_coordinator persistentStores] firstObject]; 

    NSMutableDictionary *localStoreOptions = [[self storeOptions] mutableCopy];
    [localStoreOptions setObject:@YES forKey:NSPersistentStoreRemoveUbiquitousMetadataOption];

    NSPersistentStore *newStore =  [_coordinator migratePersistentStore:store 
                                                                  toURL:[self storeURL] 
                                                                options:localStoreOptions 
                                                               withType:NSSQLiteStoreType error:nil];

    [self reloadStore:newStore];
}

- (void)reloadStore:(NSPersistentStore *)store {
    if (store) {
        [_coordinator removePersistentStore:store error:nil];
    }

    [_coordinator addPersistentStoreWithType:NSSQLiteStoreType 
                               configuration:nil 
                                         URL:[self storeURL] 
                                     options:[self storeOptions] 
                                       error:nil];
}

Switching from a local store back to iCloud is just as easy; simply migrate with iCloud-enabled options, and add a persistent store with same options to the coordinator.

(c) http://www.objc.io/issue-10/icloud-core-data.html

like image 76
kas-kad Avatar answered Nov 16 '22 20:11

kas-kad