如何为Core Data启用iCloud?

时间:2015-02-09 18:48:54

标签: ios sqlite core-data icloud

这是我第一次尝试这项工作。我正在关注iCloud Programming Guide for Core Data,“使用带有iCloud的SQLite存储”部分,并且在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服务,创建了相应的配置,并在Xcode的功能(iCloud Documents和默认容器)中启用了iCloud服务。

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

  

测试:在设备上运行该应用。如果Core Data成功创建并配置了启用iCloud的持久存储,则框架会记录一条消息,其中包含“使用本地存储:1”,以及稍后包含“使用本地存储:0”的另一条消息。

我在iPhone上运行应用程序,并且检索到persistentStoreCoordinator,但我在Xcode的调试区域中什么都没看到。

我错过了什么?

感谢?

1 个答案:

答案 0 :(得分:0)

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

我在this post找到了回复。