4

我有一个可以以两种方式运行的应用程序:使用本地存储或使用 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];
4

0 回答 0