Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefilled version of Core Data?

My app involves getting a large json file via the internet, and then parsing it into Core Data.

Thats fine, but how could I get the already filled version of this Core Data database into my app, so it is there when they first launch it. And the user can decide to refresh it later.

like image 361
cannyboy Avatar asked Aug 14 '11 15:08

cannyboy


3 Answers

There's a reasonable tutorial about pre-loading over at Ray Wenderlich's site.

Generally - create a separate project, parse the JSON file into a core data database. Create your real project, copy the Object model and the database file to this new project.

Now, at app start up, check if the database exists in the document's directory, and if it does not, copy your prefilled one from your app bundle.

Make sure that the Persistent Store Coordinator works with the database in the documents folder and not the one in the app bundle.

Update June 2012

I've got a small example project on GitHub called PromNight which demonstrates using an Xcode Workspace with an iPad project and a OS X project to preload the data for Core Data. This uses an object model that is shared between the the two applications which helps to keep changes in sync when preloading.

like image 121
Abizern Avatar answered Oct 16 '22 07:10

Abizern


Core Data uses a backing store, which is essentially a sqlite database (or, on Mac OS, optionally an XML file). You should simply add that file to your app's bundle and ship it with the app. As far as getting the data into the database, here's what I would do:

  1. Write some code to import the data from whatever format you have it in.
  2. Run that code.
  3. Copy the sqlite file off of the device or from the simulator.
  4. Add the newly created sqlite file to your project in Xcode.

I wouldn't hand-create the sqlite file, since Core Data does some "voodoo" behind the scenes and messing with the sqlite can break things. Also, I've seen developers use multiple targets. for the import. This way, they can write the code in a compiler conditional and then not have to worry as much about project maintenance. For example:

#ifdef kImportTarget

//run core data import

#else

// run the Core Data stack setup from an existing file

#endif
like image 24
Moshe Avatar answered Oct 16 '22 06:10

Moshe


The Core Data database is just a SQLite database file. You can deliver it in your main bundle and then copy it to your documents folder before associating it with your persistent store coordinator.

like image 2
adonoho Avatar answered Oct 16 '22 05:10

adonoho