Question

Is it possible to lose data if a SQLite DB is not closed properly in iOS/iPhone?

I was thinking of closing the DB in applicationWillTerminate, but want to make sure this doesn't have any nasty side-effects first.

Was it helpful?

Solution

For the most part, no; sqlite3 writes everything to "disk" (and calls fflush/fsync/etc as appropriate) before returning.

There's one big exception: If there's an uncommitted transaction when you close the database, it'll be rolled back the next time you open it.

Exactly what happens depends on PRAGMA journal_mode: if it's "memory" or "off", the database is likely to be corrupt if your app crashes during a write. I think PRAGMA locking_mode only affects what happens when locks are released, not transactional integrity.

Note that -applicationWillTerminate: is not sufficient anyway! If you haven't set UIApplicationExitsOnSuspend, the default behaviour on iOS 4 and a new-enough device (i.e. newer than iPhone 3G/iPod 2g) is to send -applicationWillEnterBackground: and then suspend your app (apparently with SIGSTOP). If the OS later decides that your app needs to exit, it sends SIGKILL without giving your app any more CPU time. You need to save state in both -applicationWillTerminate: and -applicationWillEnterBackground:; the main difference is that you can start a background task in the latter.

(The other difference is that you might do some "cleanup" in -applicationWillTerminate: that shouldn't happen when you're just moved to the background, even though freeing memory when your app is about to exit is largely a waste of CPU time.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top