Database Reference
In-Depth Information
Now let's add our method implementation in CTAppDelegate.m :
- (void)syncKVStore {
[[NSUbiquitousKeyValueStore defaultStore] synchronize];
}
It is important to note that when your app starts you should call synchronize immediately so that
your app knows to check the iCloud Key-Value Store for changes at launch. Let's add this method
call in the application:didFinishLaunchingWithOptions: method right after we verify that our
defaults are created:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)
launchOptions
{
if(![self hasDefaults])
[self createDefaults];
[self syncKVStore];
//Comment: Override point for customization after application launch.
MainViewController *controller = (MainViewController *)self.window.rootViewController;
controller.managedObjectContext = self.managedObjectContext;
return YES;
}
Now that we can write to it, how do we know if there are any changes? To be notified of changes
we need to add an observer to NSNotificationCenter . We want to listen for the message
NSUbiquitousKeyValueStoreDidChangeExternallyNotification . Let's add the following code just
after our user defaults check, but before the syncKVStore method call in the application:didFinish
LaunchingWithOptions: method:
//Comment: Register for Key-Value Store Notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(storeDidChange:)
name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification object:[NSUbiquitousKeyValueStore
defaultStore]];
Here we call the method addObserver:selector:name:object on our NSNotificationCenter object
to tell our default notification center that we want to listen for these messages and respond to them.
The first parameter we provide is our Application Delegate object that defines that we will be the one
listening for this message. The second parameter we provide is the method selector that we want to
call when this message is received. We have not added that method yet, but we will shortly. The third
parameter provided is the name of the message we are listening for. And the final parameter is the
object sender that we provide our iCloud Key-Value Store object.
Now we need to add the method storeDidChange:, which will really be the meat of our logic. This
is where you can test for conflicts and do any other logic to keep your user defaults and the iCloud
Key-Value Store in sync. Let's add that method now.
 
Search WWH ::




Custom Search