Search code examples
objective-ccore-dataios5uimanageddocument

How to convert existing non-document Core Data store to uimanageddocument?


How to import data from existing non-document Core Data store to uimanageddocument?

The question is how to copy from the old managedObjectContext to the new one.


Solution

  • The answer is to subclass UIManagedDocument, in which import(simply copy)existing store to the document store:

    - (BOOL)configurePersistentStoreCoordinatorForURL:(NSURL *)storeURL ofType:(NSString *)fileType modelConfiguration:(NSString *)configuration storeOptions:(NSDictionary *)storeOptions error:(NSError **)error
    {
        // If legacy store exists, copy it to the new location
        NSURL *legacyPersistentStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Guides.sqlite"];
    
        NSFileManager* fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:legacyPersistentStoreURL.path])
        {
            NSLog(@"Old db exists");
    
            NSError* thisError = nil;
            [fileManager replaceItemAtURL:storeURL withItemAtURL:legacyPersistentStoreURL backupItemName:nil options:NSFileManagerItemReplacementUsingNewMetadataOnly resultingItemURL:nil error:&thisError];
            NSLog([thisError localizedDescription]);
        }
    
        return [super configurePersistentStoreCoordinatorForURL:storeURL ofType:fileType modelConfiguration:configuration storeOptions:storeOptions error:error];
    }