【问题标题】:NSUbiquitousKeyValueStore not so ubiquitous?NSUbiquitousKeyValueStore 不是那么普遍吗?
【发布时间】:2015-03-05 16:51:24
【问题描述】:

我正在尝试使用 NSUbiquitousKeyValueStore 存储键值。在安装应用程序时它们似乎可以正常存储,但如果我从设备上删除应用程序并再次运行应用程序,键值似乎会丢失。这是预期的行为,还是我遗漏了什么?

我正在像这样存储和检索值:

-(void)setString:(NSString*)stringValue forKey:(NSString*)keyValue {
    NSUbiquitousKeyValueStore *iCloudStore = [NSUbiquitousKeyValueStore defaultStore];
    [iCloudStore setString:stringValue forKey:keyValue];
    [iCloudStore synchronize];
}
-(NSString*)getStringForKey:(NSString*)keyValue {
    NSUbiquitousKeyValueStore *iCloudStore = [NSUbiquitousKeyValueStore defaultStore];
    return [iCloudStore stringForKey:keyValue];
}

我已经检查过的内容:

  1. 我已在 Target Capabilities 中启用 iCloud 和键值存储。
  2. iCloud Drive 已在我的设备上启用,并且应用程序本身已启用。
  3. 我已经等了一段时间才尝试加载这些值,以确保这不仅仅是同步问题。
  4. 我已经按照Apple docs 在 NSNotificationCentre 中为 NSUbiquitousKeyValueStoreDidChangeExternallyNotification 注册了一个观察者。在安装后的第一次运行或后续运行时,永远不会调用我的观察者。我的代码(从Apple docs剥离)

    NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(updateKVStoreItems:)                                                         name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
                                           object:store];
    [store synchronize];
    
    - (void)updateKVStoreItems:(NSNotification*)notification {
        NSLog(@"RECEIVED DATA");
    }
    

其他问题 -

  1. 有没有办法知道您的数据何时已同步云端?(即上传的数据)
  2. 或者相反,有没有办法告诉您的应用何时成功同步云?(即下载的数据)我希望NSUbiquitousKeyValueStoreDidChangeExternallyNotification 会通知这一点,但因为我没有收到此通知,我怀疑这只是因为另一台设备在应用程序打开时更新了数据,Apple docs 似乎证实了这一怀疑:

    NSUbiquitousKeyValueStoreServerChange - iCloud 中更改的值。当另一台设备运行您的应用程序的另一个实例并连接到同一个 iCloud 帐户时,会发生这种情况,并上传一个新值。”

【问题讨论】:

    标签: ios objective-c icloud nsubiquitouskeyvaluestore


    【解决方案1】:

    您是否在应用程序服务中为 Apple Developer Portal 中的应用程序 ID 启用了 iCloud?之后,您还必须为应用创建配置文件。

    我在代码中看到的唯一区别是“名称:”参数。您需要指定要观察 NSUbiquitousKeyValueStoreDidChangeExternallyNotification

    [[NSNotificationCenter defaultCenter]
     addObserver: self
     selector: @selector (storeDidChange:)
     name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification
     object: [NSUbiquitousKeyValueStore defaultStore]];
    

    您的代码在我的环境中引发警告

    Instance method '-addObserver:selector:object:' not found (return type defaults to 'id')

    我也一直在使用 setObject:forKey: 而不是 setString:forKey:

    【讨论】:

    • 嗨,约翰,感谢您的评论。实际上 name 属性在我的问题中,由于一些奇怪的格式原因,它在右侧。我将配置文件设置为自动,这意味着当我在 Target Capabilities 中启用 iCloud 和键值存储时,Xcode 会自动为团队配置文件注册这些服务器。 (我在会员中心仔细检查过)
    猜你喜欢
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    相关资源
    最近更新 更多