When developing a mobile app, it’s necessary to ship the app with some default
data. I recently came across the task of pre-populating an application with a
fair amount of data and found documentation on exactly how to do this with Core
Data lacking. Maybe it’s because I’m not a seasoned Core Data expert, but
come on! Searching The Google also turned up many others having a similar hard
time finding clarity on this issue.
This article presents a method for pre-populating a Core Data application on
IOS.
Procedure
We’ll walk through the specific steps in detail, but this is the general
approach to Core Data pre-population:
Generate a Core Data database with pre-populated data
Add this database to the project
When app starts for the first time, copy the pre-populated DB into the
managed store and start application.
Profit!
Step 1: Generate a Core Data database
A common misconception about Core Data is that ‘its just a sqlite database,
gosh! ‘ Which is true; however sqlite is just one of the ways Core Data can
persist itself. The problem with this conception is the Core Data sqlite
schemea is proprietary - don’t even try opening it up with any tools because
the data and column names won’t make any sense. Changing anything may render
the DB unusable. What we need to do is somehow populate the DB via the Core
Data interface. This may require writing our own parsing code, or using an app
like Core Data Editor
In apps I’ve done, data was first extracted as JSON, manually parsed, and then
saved within Core Data.
Step 2: Add the pre-populated database to the project
Add the function we’ve created to parse and prepopulate Core Data somewhere within the Appdelegate, or
another place to be executed on launch. Next, within the AppDelegate, we need to find the
location of our newly populated sqlite file. Add this code to the
‘persistentStoreCoordinator’ in AppDelegate :
Awesome, now we gotcha!
Rename this file to something like ‘Prepopulated.sqlite’ and add it to project
as a resource.