Question

I am passing an integer value to the NSUserDefault object to store for use when my app loads up. I HAD it working perfectly until I tried to switch that integer value to a float. It caused a whole bunch of problems, so I re-adjusted my approach, and command-z'd my way back to the safety of integers...or so I thought.

It used to be that if I saved the value, I could close my simulator immediately, and the console would spit out the correctly saved number without problem. NOW, after that stupid float mess (Could I have corrupted my NSUserDefault object? That just sounds stupid...), getting the right number to display is somewhat of a gamble.

I have gone through with a bunch of NSLogs, and can confirm that the value I save when I hit save is correctly being passed to the set method in the UserDefault class. The set method gets the value correctly, and then sets it to the NSUD object like so:

[self setObject:[NSNumber numberWithInteger:num] forKey:savedNum];

When I run the get method on that object, the console prints out the value correctly. When the app loads up, it calls the SAME get method I just tested, but it doesn't always return the right thing. Often times, it is the previous save's value that shows up.

If I hit the save button and wait 5 seconds before closing the app, it has worked correctly before, but its rare. If I wait 10 seconds, it spits out the right number.

Why would time have anything to do with this operation? I am just at a complete loss as to why this is occurring, especially because I had it working correctly just yesterday...

Any thoughts or input would be appreciated!!

Was it helpful?

Solution

Did you make sure to -synchronize the NSUserDefaults?

OTHER TIPS

I've never noticed that behavior - and I don't think it is the case that there is a delay involved.

So the most obvious question is:

If you do a:

[[NSUserDefaults standardUserDefaults] setInteger:value ForKey:@"myInteger"];
NSLog(@"It is %d",[[NSUserDefaults standardUserDefaults] integerForKey:@"myInteger"]);

Do you get the correct value?

I believe this is a simulator bug. With your application on the simulated device, open up Settings.app. Now exit Settings.app. Your defaults settings will suddenly begin working.

See also this thread on the Apple discussion forums about the non-sticky NSUserDefaults issue.

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