3

Is there a way to force Core Data to create the underlying SQLite database based on your model before you actually create any entities that need to be persisted?

My objective is to define my model in the designer, have the SQLite database created and thus be able to import data into it and/or insert/update data directly thru a tool like SQLite Database browser.

TechZen
  • 64,370
  • 15
  • 118
  • 145
wgpubs
  • 8,131
  • 15
  • 62
  • 109
  • You can create a dummy record and then delete it. – Moshe Aug 09 '11 at 17:15
  • Potentially silly question, does it not create the empty database once you load up your app, or even after building the project? – Karoly S Aug 09 '11 at 17:20
  • @Karoly: Not that I've noticed. I'm new to Core Data so I could definitely be wrong – wgpubs Aug 09 '11 at 18:40
  • Directly editing a Core Data SQLite store is always risky and usually more trouble than it is worth. The SQLite schema is undocumented and it changes over time without notice. It's better to just import the data through Core Data and be done with it. – TechZen Aug 09 '11 at 20:07

1 Answers1

2

Once your managedObjectContext and persistentStore is ready, just do

[managedObjectContext save:&error];

without putting anything into the context. That'll write the database file which contain no CoreData entity to the file system.

However you can't add entities into the SQLite database backing your CoreData model without using CoreData. The way CoreData translates the object hierarchy into SQLite is an implementation detail, and it's very difficult to create a SQLite file which can be correctly and consistently interpreted by CoreData, without using CoreData itself.

If you want to treat the SQLite file as SQlite file, use SQLite directly, or use a thin wrapper around it like FMDB.

Yuji
  • 34,103
  • 3
  • 70
  • 88
  • I'll give your solution a try. As a side question, in your opinion, is Core Data really all that worth it when you have SQLite wrappers like FMDB to ease the pain of working with the database directly? Maybe its just me but I like a clean DB ... something I can understand and work with directly as well as move data into or out of efficiently. Thoughts? – wgpubs Aug 09 '11 at 18:42
  • @wgpubs -- Core Data is not a SQL wrapper. It is an object graph manager designed to create the model layer of a Model-View-Controller design app. As such, persistence is optional and something of a design after thought. Core Data saves time by handling all the runtime management of data objects for you so you don't have to rewrite object management for each app. Efficiently getting raw data on and off disk is just a secondary and optional function. – TechZen Aug 09 '11 at 20:10
  • @wgpubs -- You might want to look at one of my previous answers on when to use Core Data versus SQL or some other method: http://stackoverflow.com/questions/5237943/creating-a-json-store-for-iphone/5249674#5249674 – TechZen Aug 09 '11 at 20:11