5

For my app, I use iCloud key value storage to store some user settings. It syncs perfectly between my iPad and iPhone when both have the app installed. My issue is that when I delete the app, and I run it fresh, it doesn't have any of the settings from iCloud the FIRST TIME I run it. After I run it again, even though it didn't have the settings the first time, it has them.

I used some NSLogs to see what it sees in the key-value container, and the first time the app runs fresh it says "(null)", but any subsequent runs it prints out the NSArray that was saved previously.

I'll gladly provide code, but I'm not entirely sure what is relevant here.

I'd appreciate any help, this issue is driving me crazy...

4

2 に答える 2

6

NSUbiquitousKeyValueStoreDidChangeExternallyNotificationと syncのオブザーバーを追加し 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 に答える