Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults Values Are Lost Periodically

I use [NSUserDefaults standardDefaults] to store a boolean to see if it is the first time that application is being launched ... If so, the app should show a registration window.

  • It was working fine till last week, but now, sometimes when I switch to other apps and come back after a little while, I see that registration page loads while it shouldn't.

  • I used NSLog to see what is stored in [NSUserDefaults standardDefaults] and I see that the values I stored has been set to nil (null) while I haven't done that anywhere in my code.

Does anyone know why the values do reset ?

P.S: Actually the values are not permanently lost , because if I don't do anything in registration page and quit the app instead, It will launch normally the next time I enter the app !!!

like image 894
Sepehrom Avatar asked May 03 '14 11:05

Sepehrom


3 Answers

Here are the ways I know about to lose values in NSUserDefaults, in order of likelihood:

  1. The key was never saved in the first place
  2. Your app deletes it later on
  3. The app is deleted and reinstalled
  4. Another app overwrites or removes the key
  5. The phone or simulator is reset
  6. During the night, the phone is replaced by an identical-looking, different phone

It sounds like, from the discussion here, that you've ruled out 1,2,4, and probably 3 & 5. The only next debug step I can think of is to store the test phone in a locked drawer at all times.

But I'd leave my money on an intermittent problem causing #1. For that, we'd need posted code to investigate.

EDIT -

A high % of NSUserDefaults problems posted here are about storing BOOLs and other scalar types. It looks like the OP knows about wrapping in NSNumbers, but BOOLS in particular are fraught because it's easy to confuse false-y values like NO no and nil, and NSNull instance.

Let's throw that on the list for this question at #2.5. There again, would need code to confirm.

like image 92
danh Avatar answered Oct 19 '22 23:10

danh


A long time ago I encountered this issue, turns out a third party library that I was using uses the same key when storing values to NSUserDefaults. Try searching your project for this key, maybe something else is resetting it.

like image 40
Enrico Susatyo Avatar answered Oct 19 '22 23:10

Enrico Susatyo


If this is happening while testing, it's normal. The fact that the program is even making this decision (should I show the registration page?) suggests that the app has been forcibly quit and is starting from scratch. When testing, this can result in clearing out the app sandbox as the app is reloaded from Xcode. In the real life of a real user, however, that won't happen (unless the user deletes the app from the device).

like image 41
matt Avatar answered Oct 19 '22 22:10

matt