Database Reference
In-Depth Information
- (void)storeDidChange:(NSNotification *)notification {
// Get the list of keys that did change
NSDictionary *userInfo = [notification userInfo];
NSNumber *reasongForChange = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey];
NSInteger reason = -1;
If a reason could not be determined, we shouldn't update anything.
if(!reasongForChange)
return;
Now you will update only for changes from the server.
reason = [reasongForChange integerValue];
if(reason == NSUbiquitousKeyValueStoreServerChange || reason ==
NSUbiquitousKeyValueStoreInitialSyncChange){
NSArray *changedKeys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
NSUbiquitousKeyValueStore *kvStore = [NSUbiquitousKeyValueStore defaultStore];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[changedKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
id value = [kvStore objectForKey:key];
[userDefaults setObject:value forKey:key];
}];
}
}
This is a lot at first glance, but it will quickly make sense. This method receives an
NSNotification
object. This is the object that is sent to us whenever the message
NSUbiquitousKeyValueStoreDidChangeExternallyNotification
is received by the app. We start
off by calling the
userInfo
method to get the data or payload of the notification. It comes in the
form of an
NSDictionary
. We then extract the reason for change by getting the value for the key
NSUbiquitousKeyValueStoreChangeReasonKey
. The reason is in the form of an
NSNumber
which we
assign to the variable
reasonForChange
. Then we set up an
NSInteger
variable “reason” and assign
it a value of -1. Setting this to -1 ensures that it doesn't conflict with any of the enum values that we
will check for. We then do a check to make sure that our
reasonForChange
is not
nil
. If it is, we return
out of this method. If not, we continue on and pull out the
integerValue
and assign it to reason.
Note
Apple provides two constants to us for working with the
userInfo
dictionary of the
NSUbiquitousKeyValueStoreDidChangeExternallyNotification
notification. They are
NSUbiquitousKeyValueStoreChangeReasonKey
and
NSUbiquitousKeyValueStoreChangedKeysKey
.
Search WWH ::
Custom Search