简体   繁体   中英

NSUserDefaults sometimes returns wrong value

I save the user profile picture ID of a user as a string in NSUserDefaults eg @"12". When I do that, I call the synchronize method immediately.

When I read this value from NSUserDefaults, it returns @"12" in maybe 99% of the time. But sometimes, it returns a different value (which I cannot find due to the rarity of the event, but suspect it is either nil or some default value (?)).

The code I use to write/read is very simple:

NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:@"12" forKey:@"photoID"];
[userDefaults synchronize];

NSString* photoID=[userDefaults objectForKey:@"photoID"];

I know the value sometimes returned is incorrect because the app at the time behaves as if the value was different (ie user contacts are notified the profile picture has changed).

And when that happens, the next call to objectForKey returns the correct value, so user contacts received another notification the profile picture has changed again.

NSSynchronize is not guaranteed to succeed and returns a BOOL. Note that syncrhonize simply writes the data to disk but NSUserDefaults keeps the data in memory as well. Calling it after every write is probably not needed, though I've done it myself and many examples on the net do that.

From the Apple documentation:

use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

Disclaimer: speculation
It's possible that the act of failed synchronize is causing objectForKey to fail. The class knows the data it has may be wrong and so returns nil instead. This is more likely if you are calling synchronize successively and excessively or otherwise doing IO intensive operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM