1

我正在尝试使用 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 文档为 NSUbiquitousKeyValueStoreDidChangeExternallyNotification在 NSNotificationCentre 注册了一个观察者。在安装后的第一次运行或后续运行时,永远不会调用我的观察者。我的代码(从Apple 文档中剥离)

    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 文档似乎证实了这一怀疑:

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

4

1 回答 1

0

您是否在应用程序服务中为 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:

于 2015-01-14T19:47:15.100 回答