Objective-c – How to update SQLite DB on iPhone app update

iphoneobjective csqlite

I currently have an iPhone app in the iTunes app store that uses a SQLite database as a datastore. The user can sync the app against a web service and data that is returned is then stored in the SQLite database. The user can also insert new items into the database and sync their changes back up to the web service.

When a connection is opened to the app's local database, the code checks to confirm that the database file exists in the "Documents" folder, if it does not the database is created by being copied from the "Resources" folder to the "Documents" folder.

I have to release an update to the app. The update contains database schema changes (new tables, columns, etc.). From what I have read, files in the "Documents" directory will persisted on an app update, meaning the existing database will still be intact after the update.

My question is, how do I replace the existing database with my updated database and is there a way to do so without losing the data in the existing database? Is there some sort of "first run after update" event I can work with to do the database update, or do I have to do some sort of check on the existing database (look for a new column or table) and if my check fails manually replace/update the database?

Thanks!

Best Answer

You should store the current version number of the app somewhere persistent -- in the database or better yet in the Defaults database. On startup, your app will compare it's own version number with the persisted version number. If they differ, then this is the first run after an update. If the persisted version number isn't there, then obviously also this is the first run after an update.

As for updating your database, if it's in place you would use the usual SQL ALTER commands to update your schema, and do any database data migration at the same time.