Luke Smith
Luke Smith

Reputation: 692

Loading a database directly into CoreData

Is it possible to load a database / entity directly into CoreData? The app relies of data, the initial data load being > 100,000 items. On an iPhone 4 it's taking about 15 minutes to complete the insertion, which is an unpleasantly long time.

Is there any way I could:

  1. Load a pre-populated entity into CoreData
  2. Load a pre-populated database (all entities) into CoreData
  3. Something along these lines to make the insertion of data significantly quicker

Thanks.

Upvotes: 0

Views: 135

Answers (3)

Mundi
Mundi

Reputation: 80265

Copying a pre-made Core Data generated sqlite file via the application bundle is a good idea, even though I find it a bit cumbersome. This make most sense if you have a store for static data and one for dynamic data - in most cases it is feasible to copy the static one like this.

But nevertheless, for the record, 15 minutes is ridiculous. I can close to guarantee that you can cut this down to a few seconds.

I have been able to accomplish 500K inserts in less than 30 seconds on a first generation iPad. The most important optimisation techniques are:

  • disabling the undo manager,
  • using a background thread with @autoreleasepool,
  • saving periodically with exactly the right batch size (determine experimentally).

Upvotes: 0

Bladebunny
Bladebunny

Reputation: 1349

Yes it is possible. The 'normal' approach to this is to pre-build the database, include it as a resource, check on startup whether you have a database in the documents folder and, if not, copy it over from the bundle.

I usually run my code to build the database on the simulator, and then go copy it from the sim folder and add to my project resources.

Upvotes: 0

Owen Hartnett
Owen Hartnett

Reputation: 5935

Create your database using CoreData and add it to your project bundle, then at first load, copy the database from the bundle to the file system so it will be writable, then open it from there. You may want to mark the database as don't share to iCloud depending on your needs.

Upvotes: 1

Related Questions