您的位置:首页 > 产品设计 > UI/UE

简单的iCloud键值存储Key-Value Data Storage

2015-12-09 00:00 639 查看
摘要: Key-Value Data Storage主要用于应用的小量非关键数据在多个设备间共享,支持的数据包括:NSString, NSDate, NSArray, NSData, Boolean, NSDictionary, NSNumber等对象
NSUbiquitousKeyValueStore类
NSUbiquitousKeyValueStore *keyStore =
[[NSUbiquitousKeyValueStore alloc] init];
[keyStore setString:@”Saved String” forKey:@"MyString"];

然后调用:
[k...

#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同步。
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息