Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data move data into shared container

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?

like image 794
Mattia Confalonieri Avatar asked Apr 17 '15 13:04

Mattia Confalonieri


2 Answers

You can migrate a Core Data Stack. A fuller answer can be found here, but the short version is:

  1. Check if the old non-group copy of the data exists
  2. If it does, set up a Core Data stack using that file. Then use migratePersistentStore:toURL:options:withType:error: to move it to the new location. Then remove the old copy.
  3. If the old version doesn't exist, just set up Core Data with the new copy as usual.

(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.)

like image 66
Stephen Darlington Avatar answered Oct 09 '22 09:10

Stephen Darlington


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];
}
like image 41
Stephen Johnson Avatar answered Oct 09 '22 10:10

Stephen Johnson