iOS网络编程-iCloud键值数据存储编程实例

来源:互联网 发布:淘宝一元秒杀是真是假 编辑:程序博客网 时间:2024/04/27 16:05

iCloud键值数据存储设计

iCloud键值数据存储编程实例,画面中有两个开关控件,左图是设备1点击“设置iCloud数据”按钮,将控件状态保存到iCloud服务器。右图是设备2画面,过几秒钟后设备2收到变更通知。

 10

 

配置Xcode工程

使用Xcode创建一个iOS工程,工程创建好之后,选择TAGETS→MyNotes→Summary→Entitlements,我们可以在这里配置授权信息。

11

然后我们还需要应用设置代码签名标识,代码签名标识需要选择这个配置概要文件的。选择TAGETS→MyNotes→Code Signing Identity

12

设置完成之后可以开始编码工作了。

代码实现

首先是需要注册NSUbiquitousKeyValueStoreDidChangeExternallyNotification通知,并同步数据,代码参考ViewController.m的viewDidLoad方法:

[cpp] view plaincopy
  1. - (void)viewDidLoad  
  2.   
  3. {  
  4.   
  5. [super viewDidLoad];  
  6.   
  7. NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore]; ①  
  8.   
  9. [[NSNotificationCenter defaultCenter]  ②  
  10.   
  11. addObserverForName:  
  12.   
  13. NSUbiquitousKeyValueStoreDidChangeExternallyNotification  
  14.   
  15. object:store  
  16.   
  17. queue:nil  
  18.   
  19. usingBlock:^(NSNotification *note) { ③  
  20.   
  21. //更新控件状态  
  22.   
  23. [_switchSound setOn:[store boolForKey:UbiquitousSoundKey]]; ④  
  24.   
  25. [_switchMusic setOn:[store boolForKey:UbiquitousMusicKey]];  ⑤  
  26.   
  27. UIAlertView *alert = [[UIAlertView alloc]  
  28.   
  29. initWithTitle:@”iCloud变更通知”  
  30.   
  31. message:@”你的iCloud存储数据已经变更”  
  32.   
  33. delegate:nil  
  34.   
  35. cancelButtonTitle:@”Ok”  
  36.   
  37. otherButtonTitles:nil, nil];  
  38.   
  39. [alert show];  
  40.   
  41. }];  
  42.   
  43. [store synchronize];  ⑥  
  44.   
  45. //初始化控件状态  
  46.   
  47. [_switchSound setOn:[store boolForKey:UbiquitousSoundKey]];  ⑦  
  48.   
  49. [_switchMusic setOn:[store boolForKey:UbiquitousMusicKey]];  ⑧  
  50.   
  51.    
  52.   
  53. }  


保存数据到iCloud存储,代码ViewController.m的setData:方法:

[cpp] view plaincopy
  1. - (IBAction)setData:(id)sender {  
  2.   
  3. NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];  
  4.   
  5. //存储到iCloud  
  6.   
  7. [store setBool:_switchSound.isOn forKey:UbiquitousSoundKey];  
  8.   
  9. [store setBool:_switchMusic.isOn forKey:UbiquitousMusicKey];  
  10.   
  11. [store synchronize];  
  12.   
  13. }  
  14.   
  15. 因为是BOOL值所以存储使用的方法是setBool:forKey:。最后不要忘记解除注册的通知,在视图控制器中解除通知可以在didReceiveMemoryWarning方法中完成:  
  16.   
  17. - (void)didReceiveMemoryWarning {  
  18.   
  19. [super didReceiveMemoryWarning];  
  20.   
  21. [[NSNotificationCenter defaultCenter] removeObserver:self];  
  22.   
  23. }  


由于本应用中只有一个通知,因此可以使用[[NSNotificationCenter defaultCenter] removeObserver:self]语句解除全部通知,而不影响其它的通知,如果还有其它的通知我们要慎用这个语句。

编程完成代码我们可以测试一下,这个应用的测试很麻烦,需要两个真实设备而不能在模拟器上进行。运行两个设备,点击其中一个设备的“设置iCloud数据”按钮,过几秒钟后另外一个设备收到变更通知。

13