3

I'm using Core Data in my app and would like to export only some of the data and import it on some other device.

To avoid migration issues, I'd like to do the following:

Export:

  • create a second export.sqlite-file with the same database model, but empty
  • add that file with addPersistentStoreWithType
  • copy some ManagedObjects over to that .sqlite
  • remove the added persistent store

Import: - copy export.sqlite-file into app - add that .sqlite-file with addPersistentStoreWithType - copy data over - remove added persistentStore

but how to achieve that? i.e. how can I tell my managed object so copy itself into the other store?

swalkner
  • 16,679
  • 31
  • 123
  • 210
  • Did you achieve this? I am also having a similar problem http://stackoverflow.com/questions/33694048/coredatamigrate-data-from-bundled-db can you help me? – anoop4real Jan 22 '16 at 09:52

1 Answers1

3

how can I tell my managed object so copy itself into the other store?

You can't, not directly anyway. You'll have to do something like:

  • For each object in the origin data store,
    • Create a new object in the target store with the same entity type
    • Assign the new object's attributes to the same values as the original object
  • Once you're done creating new objects, do a second pass to set up any relationships.

The relationships need to be done separately, because all of the objects in a relationship need to exist before you can create the relationship.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • and how can I tell the managed object in which persistent store it is created and saved? – swalkner May 02 '13 at 16:14
  • 2
    When I've done something like this I used two entirely different Core Data stacks-- same model, but different persistent store coordinator and managed object context. If you want to do it with one stack, look into `NSManagedObjectContext`'s `assignObject:toPersistentStore:` method. – Tom Harrington May 02 '13 at 16:16
  • thanks a lot for your help, seems I'm getting there... now I only have to get the best way to make a deep copy... do you recommend doing it manually or is there an automatic/dynamic solution. didn't find a working one yet... – swalkner May 03 '13 at 07:24
  • 1
    If you mean the relationships, there's no automatic way. You'll need to make a lookup table when creating the new objects, and then use it when adding the relationships in the second pass. – Tom Harrington May 03 '13 at 16:05