iCloud键值数据存储设计
iCloud键值数据存储编程实例,画面中有两个开关控件,左图是设备1点击“设置iCloud数据”按钮,将控件状态保存到iCloud服务器。右图是设备2画面,过几秒钟后设备2收到变更通知。
配置Xcode工程
使用Xcode创建一个iOS工程,工程创建好之后,选择TAGETS→MyNotes→Summary→Entitlements,我们可以在这里配置授权信息。
然后我们还需要应用设置代码签名标识,代码签名标识需要选择这个配置概要文件的。选择TAGETS→MyNotes→Code Signing Identity
设置完成之后可以开始编码工作了。
代码实现
首先是需要注册NSUbiquitousKeyValueStoreDidChangeExternallyNotification通知,并同步数据,代码参考ViewController.m的viewDidLoad方法:
- (void)viewDidLoad
{
[super viewDidLoad];
NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore]; ①
[[NSNotificationCenter defaultCenter] ②
addObserverForName:
NSUbiquitousKeyValueStoreDidChangeExternallyNotification
object:store
queue:nil
usingBlock:^(NSNotification *note) { ③
//更新控件状态
[_switchSound setOn:[store boolForKey:UbiquitousSoundKey]]; ④
[_switchMusic setOn:[store boolForKey:UbiquitousMusicKey]]; ⑤
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@”iCloud变更通知”
message:@”你的iCloud存储数据已经变更”
delegate:nil
cancelButtonTitle:@”Ok”
otherButtonTitles:nil, nil];
[alert show];
}];
[store synchronize]; ⑥
//初始化控件状态
[_switchSound setOn:[store boolForKey:UbiquitousSoundKey]]; ⑦
[_switchMusic setOn:[store boolForKey:UbiquitousMusicKey]]; ⑧
}
保存数据到iCloud存储,代码ViewController.m的setData:方法:
- (IBAction)setData:(id)sender {
NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
//存储到iCloud
[store setBool:_switchSound.isOn forKey:UbiquitousSoundKey];
[store setBool:_switchMusic.isOn forKey:UbiquitousMusicKey];
[store synchronize];
}
因为是BOOL值所以存储使用的方法是setBool:forKey:。最后不要忘记解除注册的通知,在视图控制器中解除通知可以在didReceiveMemoryWarning方法中完成:
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
由于本应用中只有一个通知,因此可以使用[[NSNotificationCenter defaultCenter] removeObserver:self]语句解除全部通知,而不影响其它的通知,如果还有其它的通知我们要慎用这个语句。
编程完成代码我们可以测试一下,这个应用的测试很麻烦,需要两个真实设备而不能在模拟器上进行。运行两个设备,点击其中一个设备的“设置iCloud数据”按钮,过几秒钟后另外一个设备收到变更通知。