Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData: How to correctly use migratePersistentStore to create a backup copy

I'm really struggling with this. I'm trying to create a backup of my active core data base. According to Apple the best option is not to use the File Manager but the method migratePersistentStore. However I don't really understand this. I have my PersistentStoreCoordinator in my AppDelegate. So if I'm migrating the persistent store my coordinator will lose it after successfully moving it correctly? So the store is now just at the new location but not at the old anymore? So do you have any example program code for this of how my app still could keep running with the original copy?

Or can't i just copy all files using the filemanager with the same prefix instead of migrating?! So much easier...

like image 611
MichiZH Avatar asked Nov 01 '22 17:11

MichiZH


1 Answers

You can create a separate NSPersistentStoreCoordinator for migration only, and continue using your regular one for CoreData stack. Also you can use NSMigrationManager for migration:

NSMigrationManager* manager = [[NSMigrationManager alloc] initWithSourceModel:sourceModel
                                                             destinationModel:targetModel];

BOOL migratedSuccessfully = [manager migrateStoreFromURL:sourceStoreURL
                                                    type:type
                                                 options:nil
                                        withMappingModel:mappingModel
                                        toDestinationURL:destinationStoreURL
                                         destinationType:type
                                      destinationOptions:nil
                                                   error:error];

Also I'm not sure you can migrate when your DB is opened, probably you'll need to lock it or something.

like image 137
A.S. Avatar answered Nov 15 '22 06:11

A.S.