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?
Your problem is writing to
NSUserDefaultsdoesn’t necessarily sync that value to disk. In general,NSUserDefaultswill sync changes to disk every 30 seconds or so. What’s happening is you store aYESinNSUserDefaults, and then crash before syncing to disk, so on next launch it’s back toNOagain. The fix here is to call-[NSUserDefaults synchronize]after storing theYESvalue to force the disk synchronization to happen immediately.Note, as
-synchronizeis 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.