CoreData: Preload Data in Your iOS App

CoreData is a quick & easy way to interact with Databases in Cocoa, but it is not very straightforward to manage the actual creation of a database, for all its user-friendliness in managing Entities and Attributes.

You might want to pre-populate a CoreData store with your own data, say, as demonstration of the usage of the app (with users able to add additional data) – or as a full-fledged data store for the user to consume (like a Recipes app, with preloaded recipes). You can do this – though only using code, and not the Model Editor in Xcode.

To get started, you need an existing sqlite database with the data you want to pre-populate. The easiest way to achieve  this is to have a working app that will allow you to add & delete data, and then copy this data into the required app.

If your app allows new data entry, you can use your existing app itself for this purpose. If it doesn’t though, you’d have to slightly work around, and allow new data entry in your app or create an entirely different app. Just make sure that both apps have the same data model.

Once you have added all the required data in this app, you need to copy the sqlite database into your other app’s bundle resources. You can locate the sqlite file generated by the app simulator at

/Users/<username>/Library/Application Support/iPhone Simulator/<sdk version>/Applications/<app>/Documents

(On OS X 10.7 Lion, press cmd+shift+g, and enter the above path).

In your app, add this file in Xcode, and make sure it is included in the Bundle Resources, in your Project settings. Make sure to first rename this file to the name of the sqlite database in your actual app, if required.

Add sqlite

Next, modify the AppDelegate’s persistentStoreCoordinator method as follows:

if (__persistentStoreCoordinator != nil) {

return__persistentStoreCoordinator;

}

NSURL *storeURL = [[selfapplicationDocumentsDirectory] URLByAppendingPathComponent:@”App_Name.sqlite”];


// Add the below code

// Check if a data store already exists in the documents directory.


if( ![[NSFileManager defaultManager]

fileExistsAtPath:[storeURL path]] ) {

// If there’s no Data Store present (which is the case when the app first launches), identify the sqlite file we added in the Bundle Resources, copy it into the Documents directory, and make it the Data Store.

NSString *sqlitePath = [[NSBundle mainBundle]

pathForResource:@”App_Name” ofType:@”sqlite”

inDirectory:nil];

NSError *anyError = nil;

BOOL success = [[NSFileManager defaultManager]

copyItemAtPath:sqlitePath toPath:[storeURL path] error:&anyError];


That should do it. To test if this works, first delete the app from the simulator, so that it’s existing Documents directory is emptied. If you then Build and Run the app, it should contain the preloaded data.

 

 


					
					
			

6 comments

  1. Josh

    Hi, If I want to pre-populate my core data db with raw txt files, is there another way other that SQLite? cuz I’m not yet comfortable with SQLite.
    Thanks

    • Arvindh

      @Josh: Unfortunately, I’m not aware of any alternatives to pre-populate Core Data other than by using a pre-built Core Data-compatible store. If you’re developing for OS X, perhaps you could use an XML based store in your app (iOS does not support XML stores).

  2. Joey

    The issue I’m having is that I have no persistent store coordinator method. I used UIManagedDocument for all my core data implementations. I got to the point where I can successfully copy a preloaded Core data database but the problem is I have to re launch the app for the data to be useful. I am also not using versioning of the xcdatamodel. The only thing I can think of is that the xcdatamodel file is not aware of the imported database file’s schema until it launches a second time. Any ideas? Is something else at play here like meta data needing to be updated?
    Any insight would help, good post and thank you.

  3. Arvindh

    You don’t have to add the file in any particular folder. Just make sure that it is included in the ‘Copy Bundle Resources’ section under ‘Build Phases’ in your project settings.

    Regards,
    Arvindh

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>