5

对于我的应用程序,我使用 iCloud 键值存储来存储一些用户设置。当我的 iPad 和 iPhone 都安装了应用程序时,它可以在我的 iPad 和 iPhone 之间完美同步。我的问题是,当我删除应用程序并重新运行它时,它在我第一次运行它时没有任何来自 iCloud 的设置。再次运行后,即使第一次没有设置,它也有。

我使用了一些 NSLogs 来查看它在键值容器中看到的内容,当应用程序第一次运行时它会显示“(null)”,但任何后续运行都会打印出之前保存的 NSArray。

我很乐意提供代码,但我不完全确定这里有什么相关的。

我会很感激任何帮助,这个问题让我发疯......

4

2 回答 2

6

NSUbiquitousKeyValueStoreDidChangeExternallyNotification为和同步添加一个观察者 NSUbiquitousKeyValueStore。等待回调很快被调用。

if([[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil])
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyValueStoreChanged:)
                                                 name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
                                               object:[NSUbiquitousKeyValueStore defaultStore]];

    [[NSUbiquitousKeyValueStore defaultStore] synchronize];
}
else
{
        NSLog(@"iCloud is not enabled");
}

然后NSUbiquitousKeyValueStoreChangeReasonKey用来区分第一次同步和服务器更改同步。

-(void)keyValueStoreChanged:(NSNotification*)notification 
{
    NSLog(@"keyValueStoreChanged");

    NSNumber *reason = [[notification userInfo] objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey];

    if (reason) 
    {
        NSInteger reasonValue = [reason integerValue];
        NSLog(@"keyValueStoreChanged with reason %d", reasonValue);

        if (reasonValue == NSUbiquitousKeyValueStoreInitialSyncChange)
        {
            NSLog(@"Initial sync");
        }
        else if (reasonValue == NSUbiquitousKeyValueStoreServerChange)
        {
            NSLog(@"Server change sync");
        }
        else
        {
            NSLog(@"Another reason");
        }
    }
}
于 2012-08-16T20:52:51.087 回答
1

在安装(和启动)您的应用程序和 KVS 下载初始值之间可能存在延迟。如果您正确注册到更改通知,您应该会看到输入的值。

您的代码应始终如下所示,通常在您的-applicationDidFinishLaunching:委托方法中:

_store = [[NSUbiquitousKeyValueStore defaultStore] retain]; // this is the store we will be using
// watch for any change of the store
[[NSNotificationCenter defaultCenter] addObserver:self
      selector:@selector(updateKVStoreItems:)
      name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
      object:_store];
// make sure to deliver any change that might have happened while the app was not launched now
[_store synchronize];
于 2012-08-16T20:57:38.013 回答