Database Reference
In-Depth Information
In the if block we are checking for two change reasons NSUbiquitousKeyValueStoreServerChange
and NSUbiquitousKeyValueStoreInitialSyncChange . The ServerChange reason is what we will
receive when another instance of the app has updated, added, or removed a key-value pair.
InitialSyncChange is delivered if this is our first sync on this device. In both of these instances we
want to retrieve those values and write them to our NSUserDefaults .
Once we know we have a change we care about, we need to get the keys for those changes. We get
these by getting the object for the key NSUbiquitousKeyValueStoreChangedKeysKey and assigning it
to an NSArray we call changedKeys . Then we create a reference to our iCloud Key-Value Store and
our User Defaults Store so we can work with them.
We can now enumerate through each of the keys in the changedKeys array and write those key-value
pairs to our user defaults. We call objectForKey: on kvStore and pass it the current key assigning
the object to the variable value. Next, we call the method setObject:forKey: on userDefaults to
assign the value to the proper key.
That is all there is to it. We are now set up to receive changes from the iCloud Key-Value Store and
write changes to them. You may notice though, that we haven't called our method updateKeyValue
StoreKey:withObject yet. Let's move over to the SettingsViewController.m file and make quick
modifications.
We should start by adding another private property called isChanged that is a BOOL value.
@property BOOL isChanged; Now want to update our instance method updateDefaultForTextField:
to call the updateKeyValueStoreKey:withObject method in our Application Delegate. We do this by
first checking to see whether synchronizing our user defaults was successful. If it was, then we will
update the key-value store and set our new isChanged BOOL value to YES . Our method should now
look like this:
-(void)updateDefaultForTextField:(UITextField *)textField {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if([textField isEqual:_txtDisplayName]){
if(![[userDefaults stringForKey:CTDisplayName] isEqualToString:textField.text]){
[userDefaults setObject:textField.text forKey:CTDisplayName];
if([userDefaults synchronize])
[AppDelegate updateKeyValueStoreKey:CTDisplayName withObject:textField.text];
_isChanged = YES;
}
} else {
if(![[userDefaults stringForKey:CTFavoriteNumber] isEqualToString:textField.text]){
[userDefaults setObject:[NSNumber numberWithFloat:[textField.text floatValue]]
forKey:CTFavoriteNumber];
if([userDefaults synchronize])
[AppDelegate updateKeyValueStoreKey:CTFavoriteNumber withObject:textField.text];
_isChanged = YES;
}
}
}
 
Search WWH ::




Custom Search