Baub
Baub

Reputation: 5044

applicationWillTerminate being called on crash

I have an application that needs to know when it crashed (for debugging purposes). When the application closes, it calls - (void)applicationWillTerminate:(UIApplication *)application in the delegate.

From my understanding, it SHOULD NOT call that line when the application crashes, but for some reason it does. (I have code in there that sets a value in NSUserDefaults if the application DID NOT crash, but doesn't change a thing if it DID crash.)

A few specifics: When - (void)applicationDidBecomeActive:(UIApplication *)application is called, a NSUserDefaults key in my program is set to YES. When - (void)applicationWillTerminate:(UIApplication *)application is called, that same key is set to NO. Upon the next launch, the application checks to see if that same key is set to YES or NO. The plan was to check if the key was YES and if it was, that means it did not close correctly (i.e. crashed).

What should I use instead to check if it crashed or not?

Upvotes: 3

Views: 1904

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185671

Your problem is writing to NSUserDefaults doesn't necessarily sync that value to disk. In general, NSUserDefaults will sync changes to disk every 30 seconds or so. What's happening is you store a YES in NSUserDefaults, and then crash before syncing to disk, so on next launch it's back to NO again. The fix here is to call -[NSUserDefaults synchronize] after storing the YES value to force the disk synchronization to happen immediately.

Note, as -synchronize is relatively expensive, you should only use it when you absolutely need to ensure the value is written to disk immediately. The case you describe qualifies. Very few other cases do.

Upvotes: 5

Related Questions