Database Reference
In-Depth Information
the same as when we construct a Core Data stack. We determine where the
documents directory is located via a call to the
NSFileManager
, and then we
append a path component to the end to identify our document. In this case,
the document is called PPRecipes.
The second URL—the iCloud URL—is a bit different.
-URLForUbiquityContainerIden-
tifier:
is a new addition to the
NSFileManager
that came with iCloud. This call
requests a
URL
in which to store information that iCloud is going to use to
sync the
NSPersistentStore
. If iCloud is disabled on the device (iOS or OS X), this
call returns
nil
. Once we have a
URL
and it is not
nil
, we know iCloud is avail-
able, and we need to configure it.
It is the second call that has an interesting issue; specifically, this call can
take an indeterminate amount of time. If iCloud is not available or if the
directory structure had previously been constructed, this call could return
nearly instantaneously. However, if iCloud is enabled and the directory
structure needs to be constructed, the call might take a significant amount
of time—long enough that we need to worry about the watchdog killing it for
taking too long to launch. Therefore, because of this method call, we need to
wrap all of this construction in a dispatch queue and let it run asynchronously
with the main thread.
Once we know whether iCloud is available, we can continue with our
configuration.
Configuring iCloud
To add iCloud to a Core Data stack, we need to add some additional options to
the
NSPersistentStore
when we add the
NSPersistentStore
to the
NSPersistentStoreCoordinator
.
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setValue:[NSNumber numberWithBool:YES]
forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setValue:[NSNumber numberWithBool:YES]
forKey:NSInferMappingModelAutomaticallyOption];
if
(cloudURL) {
cloudURL = [cloudURL URLByAppendingPathComponent:@
"PPRecipes"
];
[options setValue:[[NSBundle mainBundle] bundleIdentifier]
forKey:NSPersistentStoreUbiquitousContentNameKey];
[options setValue:cloudURL
forKey:NSPersistentStoreUbiquitousContentURLKey];
}