使用iCloud进行轻量级迁移

时间:2013-11-09 16:18:20

标签: core-data icloud database-migration

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

0 个答案:

没有答案