NSUserDefaults objectForKey sometimes nil

I just noticed that the key that exists in my **NSUserDefaults** often returns zero. It seems that in about half of the cases it’s right, and the other half doesn’t. I say half the time, but I do not mean that it flip-flopping, its only 40-50%, I see that it does not work. When I write the initial value, I immediately call the synchronization. I use this key as an application revision, which I installed when a new user signs up.

The following code returns nil:

 #define kDBrevision @"revision" NSString *rev = [[NSUserDefaults standardUserDefaults] objectForKey:kDBrevision]; 

When I run the application and simply track the value (without writing down any NSUserDefaults), sometimes this value is without any changes to NSUserDefaults.

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSString *r = [[NSUserDefaults standardUserDefaults] objectForKey:kDBrevision]; NSLog(@"revision %@", r); _exit(1); 

I have no idea why this is happening. Im running iOS 10 on my device connected to Xcode 8.2.1. Does anyone have any ideas? Thanks

EDIT: I started talking with an apple about fixing this and found out that if you have file protection completed, this might be the cause of this problem from time to time, however the apple told me that my special case (which is the only one on which I was sure at this time) is a mistake. The fact is that you use Xcode to run the application on the device, which should not be the way it sometimes happens. I do not know when and if to be fixed. Instead, I moved my critical strings from the defaults, using a keychain instead.

+5
source share
2 answers

This seems to be a bug in Xcode 8 and / or iOS 10. I came across it myself and finally narrowed the matter down so that UserDefaults would intermittently return zero when there really was data for the key. In particular, I installed the data once, then deleted the given logic and executed only the get logic, repeatedly and sometimes got values, sometimes got zero.

I changed the startup scheme to use the Release configuration, and ran the application on the device without an attached debugger, and the problem disappeared, that is, the get logic produced the correct value every time I executed it (~ 30 times).

Here are some more discussions:

iOS 10 with Xcode GM 8 caused NSUserDefaults to break in order not to work

iOS 10, NSUserDefaults not working

https://forums.developer.apple.com/thread/48700

https://forums.developer.apple.com/message/143155#143155

+5
source

try below code in didFinishLaunchingWithOptions file

Swift 3.0

 UserDefaults.standard.synchronize() 

Obective - C

 [[NSUserDefaults standardUserDefaults] synchronize]; 
0
source

Source: https://habr.com/ru/post/1263081/


All Articles