Julian7 Julian7 - 3 months ago 9
iOS Question

When does a CoreData persistent store get created?

When my app first appears on an iPhone or iPad, how does CoreData's persistent store (assume SQLite) get there?


  • Does it get created automatically when the app first runs?

  • Do I have to create it with code?

  • Does it get created by Xcode and deployed with the app?



If it gets deployed with the app, how do I know it won't be full of test data? Conversely, if I wanted it to be pre-populated with some data, how would I do that?

Answer

Does it get created automatically when the app first runs?

Yes - the addPersistentStore... method on the persistent store coordinator creates the database file if it does not already exist. This is done as part of the template code. It's slightly different in iOS10 with the new NSPersistentContainer but the principle is the same.

Do I have to create it with code?

See above - the framework classes create it for you.

Does it get created by Xcode and deployed with the app?

No - the model does, and that is used to create the database at run time in the documents directory. If it was deployed with the app it would be in the bundle, and would be read-only. Databases created while developing exist in the documents directory of your test devices and are not part of the built product.

If you want to include seed data then the easiest way is to make a separate app (probably a Mac app) which shares the same model. You can then use this to manage your seed data, and add the resulting data into your main app's bundle. On first run you then copy this data from the bundle to the documents directory before creating the persistent store.

I wrote about this approach here, note that this was quite a while ago so some things might have changed.