ローカル ストレージを使用する方法と iCloud を使用する方法の 2 つの方法で実行できるアプリがあります。ローカル ストレージを使用する場合、軽量の移行は問題なく機能しますが、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];