I am working on an application that incorporates iCloud syncing of its Core Data store (simple application with a single store/model/context). Since the store also contains image data, it has the possibility for getting quite large and so I would like to add a setting to allow the user to disable the syncing if they wish. I have looked at some sample code for using Core Data in both scenarios, and it looks to me that the only real difference between running with iCloud enabled and disabled are the options passed to the NSPersistentStoreCoordinator when it is added. As such, I had though about doing something like this:
NSPersistentStoreCoordinator *psc;
NSDictionary* options;
//Set options based on iCloud setting
if ([enableSwitch isOn]) {
options = [NSDictionary dictionaryWithObjectsAndKeys:
@"<unique name here>", NSPersistentStoreUbiquitousContentNameKey,
cloudURL, NSPersistentStoreUbiquitousContentURLKey,
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
} else {
options = nil;
}
//Add the coordinator
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
//Handle error
}
So, I have a couple of questions about the above:
- Is my assumption correct, or is there more between the two states that needs to be different?
- Often in examples this code is called in the application delegate, so it usually is only called once per application run. Is there a good strategy to responding to the necessary change on demand as the user toggle the setting?
Thanks!
This is the solution that I came up with, and it is working pretty well. Basically the code below is placed in a method that you can call when your application starts up, or anytime the your user-facing “Enable iCloud Sync” setting changes. All that needs to change between the two operation modes is the
NSPersistentStoreinstance, the underlying model file and the coordinator need no changes.My application only has one persistent store to worry about, so upon calling this method, it just removes all stores currently attached to the coordinator, and then creates a new one with the appropriate options based on the user settings.
If you have an application that utilizes multiple stores, you may need to keep references around to the stores that you want to enable/disable sync on so you can have a smarter approach rather than just blowing them all away every time.