#import "iCloud01.h"
@interface iCloud01 ()
@property (strong, nonatomic) IBOutlet UITextField *textfield;//上传到云端的数据
@property (strong, nonatomic) IBOutlet UILabel *displayValye;//下载同步到终端的数据
@property (nonatomic, strong) NSUbiquitousKeyValueStore * keyStore;//查询对象
@end
@implementation iCloud01
- (void)viewDidLoad {
[super viewDidLoad];
_keyStore = [[NSUbiquitousKeyValueStore alloc]init];
NSString * storedString = [self.keyStore stringForKey:@"paid"];
NSLog(@"Value is%@\n",storedString);
if (storedString)
{
self.displayValye.text = storedString;
}
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(ubiquitousKeyValueStoreDidChange) name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification object:self.keyStore];
// Do any additional setup after loading the view.
}
- (IBAction)buttonPressed:(id)sender
{
//保存到云端
[_keyStore setString:self.textfield.text forKey:@"paid"];
[_keyStore synchronize];//进行同步
}
- (void)ubiquitousKeyValueStoreDidChange
{
UIAlertController * controller = [UIAlertController alertControllerWithTitle:@"提示" message:@"iCloud关键字paid对应值有变化" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
[controller addAction:action];
[self presentViewController:controller animated:YES completion:nil];
_displayValye.text = [_keyStore stringForKey:@"paid"];
}
//- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
NSUbiquitousKeyValueStore
它最多能存储1M的数据,最多可以同时存储1024个键(Key),单个值不能超过1M。
单个键的长度在UTF8编码时不能超过64个字节
当你注册NSUbiquitousKeyValueStoreDidChangeExternallyNotification监听时务必要指定默认的NSUbiquitousKeyValueStore对象(通过类方法defaultStore获取)为要监听的对象
同步方法synchronize并没有立刻将所有的设置都写入iCloud,而只是保存到磁盘。可能需要一段时间才能和iCloud同步。
*/
转载于:https://my.oschina.net/AChang/blog/541288