如何为 Core Data 启用 iCloud?

How to enable iCloud for Core Data?

这是我第一次尝试完成这项工作。我正在关注 iCloud Programming Guide for Core Data、"Using the SQLite Store with iCloud" 部分,在 AppDelegate 中我有:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
   // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
   if (_persistentStoreCoordinator != nil) {
       return _persistentStoreCoordinator;
   }

   // Create the coordinator and store

   _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
   NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MyApp.sqlite"];
   NSError *error = nil;
   NSString *failureReason = @"There was an error creating or loading the application's saved data.";

   // To enable iCloud
   NSDictionary *storeOptions = @{NSPersistentStoreUbiquitousContentNameKey: @"MyAppCloudStore"};

   if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:storeOptions error:&error]) {
       // Report any error we got.
       NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
       dict[NSLocalizedFailureReasonErrorKey] = failureReason;
       dict[NSUnderlyingErrorKey] = error;
       error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
       // Replace this with code to handle the error appropriately.
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
       NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
       abort();
   }

   return _persistentStoreCoordinator;
}

之前我为这个App ID开启了iCloud服务,创建了相应的provisioning,在Xcode的capabilities(iCloud Documents和default container)中开启了iCloud服务。

根据iCloud Programming Guide for Core Data,此时:

Test: Run the app on a device. If Core Data successfully created and configured an iCloud-enabled persistent store, the framework logs a message containing “Using local storage: 1,” and, later, another message containing “Using local storage: 0”.

我 运行 iPhone 上的应用程序被检索到 persistentStoreCoordinator,但我在 Xcode 的调试区域中什么也看不到。

我错过了什么?

谢谢?

我发现了问题:[[NSFileManager defaultManager] ubiquityIdentityToken] 返回 nil,这是因为我的设备没有更新到 iCloud Drive

我在 this post 中找到了回复。