我正在使用核心数据进行 iCloud 同步工作正常。现在我想添加开/关开关(迁移商店)。如果我将商店迁移到 iCloud 到本地工作正常,但如果迁移回 iCloud 数据会重复。即使我尝试在迁移之前删除无处不在的容器也无济于事。我无法进行重复数据删除,因为在重复数据后未调用“StoreDidImportUbiquitousContent”方法。
下面的代码:
// Migrate to local
-(NSURL *)localStoreURL
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LocalExpns.sqlite"];
return storeURL;
}
- (void)moveStoreToLocal
{
NSError *error = nil;
NSPersistentStoreCoordinator * persistentStoreCoordinator = self.persistentStoreCoordinator;
NSPersistentStore * persistentStore = [[persistentStoreCoordinator persistentStores] firstObject];
if([[NSFileManager defaultManager]fileExistsAtPath:[self localStoreURL].path])
{
NSLog(@"File exists");
[[NSFileManager defaultManager] removeItemAtPath:[self localStoreURL].path error:& error];
NSLog(@"Removing error = %@", error);
}
NSMutableDictionary *localStoreOptions = [[self localStoreOptions] mutableCopy];
[localStoreOptions setObject:[NSNumber numberWithBool:YES] forKey:NSPersistentStoreRemoveUbiquitousMetadataOption];
id result = [persistentStoreCoordinator migratePersistentStore:persistentStore toURL:[self localStoreURL] options:localStoreOptions withType:NSSQLiteStoreType error:&error];
}
上面的代码工作正常。
// 迁移回 iCloud
// fileURL 是本地文件 url
-(NSURL *)storeURL
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Expns.sqlite"];
return storeURL;
}
- (void)moveStoreFileToICloud:(NSURL*)fileURL
{
NSPersistentStoreCoordinator * persistentStoreCoordinator = self.persistentStoreCoordinator;
id sourceStore = [[persistentStoreCoordinator persistentStores] firstObject];
if (!sourceStore) {
NSLog(@" failed to add old store");
} else {
NSLog(@" Successfully added store to migrate");
bool moveSuccess = NO;
NSError *error;
NSLog(@" About to migrate the store...");
// Now migrate the store using the iCloud options
id migrationSuccess = [self.persistentStoreCoordinator migratePersistentStore:sourceStore toURL:[self storeURL] options:[self icloudStoreOptions] withType:NSSQLiteStoreType error:&error];
if (migrationSuccess) {
moveSuccess = YES;
NSLog(@"store successfully migrated");
// Now delete the local file
if (shouldDelete) {
NSLog(@" deleting local store");
[self deleteLocalStore];
} else {
NSLog(@" not deleting local store");
}
}
else {
NSLog(@"Failed to migrate store: %@, %@", error, error.userInfo);
}
}
}
现在数据在迁移之前得到了重复。我试图删除无处不在的容器也没有帮助。