I have an already published app that use core data.
Now I want to add support for watch kit and today extension.
I need to move core data into shared container without lose previous user saved data, how can I do that in the best way?
You can migrate a Core Data Stack. A fuller answer can be found here, but the short version is:
migratePersistentStore:toURL:options:withType:error:
to move it to the new location. Then remove the old copy.(The problem with Stephen's answer is that it assumes that the Core Data stack is a single SQLite file, which isn't always true.)
Here is how I moved core data to the shared container in my app. I do this when the app launches.
NSUserDefaults* sharedDefs = [GPMapCore sharedCore].sharedUserDefaults;
if (![sharedDefs boolForKey:@"CoreDataMovedToExtension"])
{
NSURL* oldLocation = GET_LOCATION_OF_CORE_DATA_SQLITE_FILE();
NSURL* newLocation = GET_LOCATON_TO_MOVE_THE_SQLITE_FILE_TO();
if ([[NSFileManager defaultManager] fileExistsAtPath:[oldLocation filePathString]])
{
//Check if a new file exists. This can happen when the watch app is run before
//Topo Maps+ runs and move the core data database
if ([[NSFileManager defaultManager] fileExistsAtPath:[newLocation filePathString]])
{
[[NSFileManager defaultManager ] removeItemAtURL:newLocation error:nil];
}
[[NSFileManager defaultManager] moveItemAtURL:oldLocation toURL:newLocation error:nil];
}
[sharedDefs setBool:YES forKey:@"CoreDataMovedToExtension"];
[sharedDefs synchronize];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With