János
János

Reputation: 35050

Copy records between persistent stores in core data?

I want to copy data from one store to an other. Destination persistent store could already have records. Is it any easier way, than manually go though all the records and insert into the new context and save?

Upvotes: 2

Views: 697

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

If you want to copy all of the data, you can use migratePersistentStore:toURL:options:withType:error:, which is a method on NSPersistentStoreCoordinator. This will effectively copy the entire persistent store to a new persistent store file. Some things to be aware of:

  • Despite the name, this method has nothing at all to do with model versioning. Both use the word "migrate" but they're different processes.
  • You should be sure that you have saved all outstanding changes before attempting this.
  • After doing this, the store that you're migrating from is removed from the coordinator-- which means that
    • Any existing references to managed objects are now invalid. You should re-fetch them.
    • If you continue using the coordinator, you're using the new store file.

If you don't want to copy all of the data, you need to do it "by hand", fetching objects from the old store and creating equivalent objects in the new one.

Upvotes: 4

Related Questions