Core data 使用iCloud进行轻量级迁移

Core data 使用iCloud进行轻量级迁移,core-data,icloud,database-migration,Core Data,Icloud,Database Migration,我有一个应用程序可以通过两种方式运行:使用本地存储或使用iCloud。当我使用本地存储时,我的轻量级迁移工作正常,但当我选择iCloud时,它会导致我所有的数据丢失。以下是我用来初始化持久存储协调器的代码: NSMutableDictionary *options = [NSMutableDictionary dictionary]; NSFileManager *fm = [NSFileManager defaultManager]; NSURL *ubContainer = [fm URL

我有一个应用程序可以通过两种方式运行:使用本地存储或使用iCloud。当我使用本地存储时,我的轻量级迁移工作正常,但当我选择iCloud时,它会导致我所有的数据丢失。以下是我用来初始化持久存储协调器的代码:

NSMutableDictionary *options = [NSMutableDictionary dictionary];

NSFileManager *fm = [NSFileManager defaultManager];
NSURL *ubContainer = [fm URLForUbiquityContainerIdentifier:nil];
NSURL *logsDir = [ubContainer URLByAppendingPathComponent:@"logsDir"];

[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];


if ([[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsUseICloud]) {

    // Construct the dictionary that tells Core Data where the transaction log should be stored
    [options setObject:@"comcompanyappname" forKey:NSPersistentStoreUbiquitousContentNameKey];
    [options setObject:logsDir forKey:NSPersistentStoreUbiquitousContentURLKey];


}

// Read in xcdatamodeld
model = [NSManagedObjectModel mergedModelFromBundles:nil];

psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];


NSURL *nosyncDir = [ubContainer URLByAppendingPathComponent:@"appname.nosync"];
NSURL *storeURL;

if (ubContainer) {
    [fm createDirectoryAtURL:nosyncDir withIntermediateDirectories:YES attributes:nil error:nil];
    storeURL = [nosyncDir URLByAppendingPathComponent:@"store.data"];
}
else{
    NSString *path = [self itemArchivePath];
    storeURL = [NSURL fileURLWithPath:path];
}



NSError *error = nil;

[psc lock];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    [NSException raise:@"Open failed" format:@"Reason: %@", [error localizedDescription]];
}
[psc unlock];

// Create the managed object context
context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:psc];
[context setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];

// The managed object context can manage undo, but we don't need it
[context setUndoManager:nil];

你解决了这个问题吗?谢谢,我遇到了同样的问题。它为storeWillChange和storeDidChange通知触发InitialImportCompleted转换类型,这似乎异常。你已经解决了这个问题吗?谢谢