Thompson
Thompson

Reputation: 1098

Save objects from multiple stores to single persistent store

I have two persistent stores with objects that use the same model. I would like to open both stores in one context, but save the context to only a single store, and then safely delete one of the stores. I am in essence trying to merge the contents of two persistent stores into a single persistent store. Because the entities have relationships, I am finding this difficult.

From this answer:

If you do need to have relationships between the objects in both stores, or you really just want to have a single store, your best bet would be to create a second NSPersistentStoreCoordinator and a third, distinct persistent store to hold the merged object graph. You will need to write code to create copies of the objects in a managed object context attached to this second NSPersistentStoreCoordinator. You'll need to set up the same relationships among the copies that the original objects had, too, but how you go about doing this depends on your data model.

That makes it seem clear, except for the details of how, literally, to make copies of the objects for the new store. Is this a migration issue?

Upvotes: 2

Views: 1164

Answers (1)

Thompson
Thompson

Reputation: 1098

Ultimately, I used the following approach:

[migrator migrateStoreFromURL:[NSURL fileURLWithPath:incomingPath]
                         type:nil 
                      options:nil 
             withMappingModel:managedObjectModel 
             toDestinationURL:[NSURL fileURLWithPath:finalPath] 
              destinationType:nil 
           destinationOptions:nil 
                        error:&err];

[persistentStoreCoordinator removePersistentStore:[[persistentStoreCoordinator persistentStores]lastObject] error:&err];

The file at "incomingPath" was the store I imported, the file at "finalPath" the already-existent store that I wanted to merge into. Both stores were open in the same persistent coordinator, and both use the same object model. I then removed the incoming store and never looked at it again; I suppose I could have deleted it at the file system level.

For my particular data needs, I then fetched all the records, culled out the duplicates, and saved the context.

I publish this answer because as a core data newbie this simple migration solved the "can't save relationships to objects in different stores" problem non-intuitively.

Upvotes: 1

Related Questions