iCloud:在IOS和OSX之间同步核心数据

我尝试在IOS和OSX之间同步核心数据。 在这两个应用程序我有相同的configuration:

在这里输入图像说明

和相同的权利:

在这里输入图像说明

我也使用相同的代码为商店协调员同名的sqlite文件和url:

NSManagedObjectModel* managedModel = [NSManagedObjectModel mergedModelFromBundles:nil]; NSPersistentStoreCoordinator* storeCooordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedModel]; //-> start iCloud dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURL* applicationFilesDirectory = [JHDCoreDataDAO applicationFilesDirectory]; NSURL* storeURL = [applicationFilesDirectory URLByAppendingPathComponent:DATABASE_NAME]; if(!storeURL) { NSLog(@"Error reading applicationFilesDirectory for given sqlite resouce"); } NSString* containerIdentifier = [NSString stringWithFormat:@"%@.%@",TEAM_IDENTIFIER,APP_IDENTIFIER]; NSURL* iCloud = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:containerIdentifier]; NSString *iCloudEnabledAppID = @"TEAMID~com~sample~sample"; NSError* persistentStoreError; if (iCloud) { NSLog(@"iCloud is working"); NSLog(@"iCloudEnabledAppID = %@",iCloudEnabledAppID); NSLog(@"iCloud URL: %@",iCloud); NSString* cloudPath = [[iCloud path] stringByAppendingPathComponent:@"data"]; NSURL* transactionsLogUrl = [NSURL fileURLWithPath:cloudPath]; NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys: iCloudEnabledAppID, NSPersistentStoreUbiquitousContentNameKey, transactionsLogUrl, NSPersistentStoreUbiquitousContentURLKey, [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; [storeCooordinator lock]; if(![storeCooordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&persistentStoreError]) { NSLog(@"Fehler: %@, %@", persistentStoreError.localizedDescription, persistentStoreError.userInfo); abort(); } [storeCooordinator unlock]; } else { //Handle local psc } }); 

每个应用程序,IOS版本和OSX版本,仍然在iCloud中完美运行。 每个应用程序处理自己的数据库,因为这两个应用程序之间没有同步。 有什么我忘记的东西吗?

您需要非常小心,您在授权中使用的标识符与您在源代码中使用以访问无处不在容器的内容相匹配。

同步多个应用程序(例如Mac应用程序和iOS应用程序)的一个复杂因素是您需要检查它们各自是否具有相同的团队标识符。 如果没有,则需要明确填写iCloud授权的团队ID,而不是使用TeamIdentifierPrefixvariables。 select一个团队ID并使用这两个应用程序。

在您的特定示例中,您似乎拥有以sample.sample.sample结尾的容器标识的权利设置。 假设每个应用的团队ID都是相同的,那么您的容器ID应该是XXXXXXXXXX.sample.sample.sample ,其中第一部分是您的团队ID。 我不知道在这个实例中有什么APP_IDENTIFIER ,但是应该检查它是否是sample.sample.sample 。 (我猜是不是。)

NSPersistentStoreUbiquitousContentNameKey设置基本上可以是任何您喜欢的商店标签。 它不必使用〜甚至是反向DNSforms。 例如,您可以将其称为“Store1”。

我find最简单的方法来查看是否一切正常设置好的是去你的Mac上的~/Library/Mobile Documents文件夹,并寻找应用程序容器。 您可以直接在Finder中浏览内容。

不幸的是,这可能是让Core Data与iCloud一起工作的最简单的部分。 会有更多的障碍,他们往往更具挑战性。 有一些新的解决scheme可以随时同步Core Data,包括TICDS框架和Core Data Ensemble ,这两个工具都可以在iCloud上使用。 (披露:我对这两个项目都做出了贡献,并创立了Ensembles项目。)