Mattia Confalonieri
Mattia Confalonieri

Reputation: 147

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?

Upvotes: 7

Views: 1824

Answers (2)

Stephen Darlington
Stephen Darlington

Reputation: 52565

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

Upvotes: 5

Stephen Johnson
Stephen Johnson

Reputation: 5121

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];
}

Upvotes: 2

Related Questions