我试图在我的持久存储选项中使用NSPersistentStoreUbiquitousContentNameKey.不幸的是,此选项启用iCloud,但不将任何本地数据传输到iCloud.我似乎不能得到migratePersistentStore:toURL:options:withType:error:也可以工作.我提供持久存储,其URL,iCloud选项等,它仍然不会将现有本地数据迁移到iCloud.以下是我使用的方法:
- (void)migratePersistentStoreWithOptions:(NSDictionary *)options { NSError *error; self.storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[Nsstring stringWithFormat:@"%@.sqlite",self.sqliteFileName]]; NSPersistentStore *store = [self.persistentStoreCoordinator migratePersistentStore:self.persistentStoreCoordinator.persistentStores.firstObject toURL:self.storeURL options:options withType:NSsqliteStoreType error:&error]; if (store) NSLog(@"[CoreData Manager] Store was successfully migrated"); else NSLog(@"[CoreData Manager] Error migrating persistent store: %@",error); }
本地存储与iCloud存储分开.如果可能,我想将本地Core Data移动到iCloud,而无需手动转移每个实体.
有任何想法吗?我可以找到很多关于从iCloud移回本地存储的文章,教程和帖子 – 但是我想从本地存储迁移到iCloud.
解决方法
>创建一个本地的NSPersistentStoreCoordinator
>将现有的永久存储添加到该协调器,并存储对此新返回的存储的引用.
>调用方便的migratePersistStore:…从#2提供商店,该文件目录中的商店的URL与不同的文件名以及包括NSPersistentStoreUbiquitousContentNameKey密钥在内的所有重要选项.
这是代码,在线注释.
NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; //This is the path to the new store. Note it has a different file name NSURL *storeURL = [documentsDirectory URLByAppendingPathComponent:@"TestRemote.sqlite"]; //This is the path to the existing store NSURL *seedStoreURL = [documentsDirectory URLByAppendingPathComponent:@"Test.sqlite"]; //You should create a new store here instead of using the one you presumably already have access to NSPersistentStoreCoordinator *coord = [[NSPersistentStoreCoordinator alloc] initWithManagedobjectModel:self.managedobjectModel]; NSError *seedStoreError; NSDictionary *seedStoreOptions = @{ NSReadOnlyPersistentStoreOption: @YES }; NSPersistentStore *seedStore = [coord addPersistentStoreWithType:NSsqliteStoreType configuration:nil URL:seedStoreURL options:seedStoreOptions error:&seedStoreError]; NSDictionary *iCloudOptions = @{ NSPersistentStoreUbiquitousContentNameKey: @"MyiCloudStore" }; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //This is using an operation queue because this happens synchronously [queue addOperationWithBlock:^{ NSError *blockerror; [coord migratePersistentStore:seedStore toURL:storeURL options:iCloudOptions withType:NSsqliteStoreType error:&blockerror]; NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; [mainQueue addOperationWithBlock:^{ // This will be called when the migration is done }]; }];
请注意,执行此迁移后,您需要使用新URL配置您与MOC一起使用的永久存储,并始终将上述iCloudOptions包含在NSPersistentStoreUbiquitousContentNameKey密钥中.
这是基于Apple’s documentation.
完成后,您应该在标有CoreDataUbiquitySupport的模拟器文件夹(〜/ Library / Application Support / iPhone Simulator / …)中的Documents文件夹中看到一个新文件夹.你的iCloud嵌套深入sqlite存储.
田田!
编辑:哦,确保你已经创建了一个iCloud的权利,并将其包含在你的包中.您应该能够在Xcode中完成所有操作,但您也可以在开发门户上进行更新.