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

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值