4

I'm trying to create an app which will store data locally using coredata. Then I want to share/export that data(from coredata) to be used by other devices using same app.

Is it possible to send a coredata from one device to another? Can I just copy the *.sqlite file and overwrite the coredata in the other device?

I saw this post how to export Core Data to CSV that allow core data to be exported as csv, But what I'm trying to achieve is to pass core data itself.

Thank You!

2
  • Are you asking how to synchronize your data between devices?
    – user4151918
    Commented Jan 8, 2016 at 7:28
  • 1
    Yes. But I want to do it locally, maybe using bluetooth or any peer to peer communication Commented Jan 27, 2016 at 19:16

2 Answers 2

5

You can use migratePersistentStore:toURL:options:withType:error: of NSPersistentStoreCoordinator to save the store to a file. Once you have the file you can copy it to the other devices.

Other solutions might include iCloud if you're wanting data synchronisation.

1
  • Thank you for this. I'll research about it. Commented Jan 27, 2016 at 19:16
3

This blog post suggests a good way to export the database as one file. Besides using the migratePersistentStore:toURL:options:withType:error: method, it also creates a copy of the NSPersistentStoreCoordinator to keep the current database consistent, and disables the sqlite write ahead and log to reduce all database to just one file.

In the device receiving the sqlite file, the following worked fine for me:

1 - Save the URL of the persistent store (persistentContainer.persistentStoreDescriptions.first?.url)

2 - Delete the current persistent store, calling persistentStoreCoordinator.remove on your store instance inside persistentStoreCoordinator.persistentStores

3 - Saving the new database in the URL of the old one, using FileManager.default.replaceItem with the URL saved on the first step and the received file.

4 - Call persistentStoreCoordinator.addPersistentStore to add the store to the list of stores that core data will manage.

Also, before executing this whole process it might be good to reset all contexts (context.reset) to ensure no reference was kept, and in my case I executed everything inside the persistentStoreCoordinator.performAndWait method to avoid concurrency problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.