SQLite to Core Data Migration

Question!

I have a live app on App Store which uses SQLite as database, now with the next update I want to implement Core Data in App loading all data from .sqlite file without breaking the App. I have been reading tutorials but it didn’t help much. I don't know how to proceed. Please, point me in right direction.



Answers
From the core data documentation:

How do I use my existing SQLite database with Core Data?

You do not, unless you import your existing SQLite database into a Core Data store. Although Core Data supports SQLite as one of its persistent store types, the database format is private. You cannot create a SQLite database using the native SQLite API and use it directly with Core Data. If you have an existing SQLite database, you need to import it into a Core Data store. In addition, do not manipulate an existing Core Data-created SQLite store using the native SQLite API

You can try with the tool https://github.com/tapasya/Sqlite2CoreData but it seems quite outdate.



I think @SaintThread hit the main issue here. The reason for it is that Core Data is not a wrapper around SQLite-- it's a different API with different assumptions that just happens to use SQLite internally. Core Data doesn't attempt to be compatible with how you'd use SQLite if you were using SQLite on its own.

That said, if you still want to migrate, you'll have to design a Core Data model and then write fully custom code to migrate from your existing SQLite file to Core Data. Your code would need to read everything from SQLite, convert it to the new Core Data representation, save the changes, and then remove the existing SQLite files.

When removing the existing SQLite file, make sure to also remove the SQLite journal files (if any).



The difficulty mainly depends upon how well your code architecture is set up. There is no simple procedure to do so... Adding Core data to the project if fairly simple, understanding it is quite another matter.

Here is a few things that you might want to pay attention:

  • CoreData create the sqlite file in its own way, meaning you cannot feed it any .sqlite file and hope for the best. You will have to let CoreData create its own file and transfert the data from your sqlite store to the core data's one.

  • Your tables become class (as in most ORM, it's called Entities) and you cannot instantiate a new entity directly, meaning that if you have a table Employee, you cannot do Employee * john = [[Employee alloc]init]; That won't do! Inserting element is the responsibility of the NSEntityDescritpion class. So check your code for possible mistake there...

If core data is a bit to complicated, Realm is a good ORM alternative : https://realm.io/products/objc/

Good luck...



This video can help you solving your question :)
By: admin