NSUserDefaults not working correctly

You have problems with NSUserDefaults here.

This is how I create it:

 NSString *theCity = @"Test City"; [[NSUserDefaults standardUserDefaults] setObject:theCity forKey:@"SavedCity"]; 

This is how I try to restore it:

 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"SavedCity"]) { NSLog(@"Key exists! %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"SavedCity"]); } else { NSLog(@"No city saved!"); } 

The problem is that even if there is a key for "SavedCity" (I check the pref file in the Simulator directory), it always displays "No city saved". Am I doing something wrong?

Thanks!

+4
source share
3 answers

Two things you could try.

1) Try synchronizing user defaults after line settings. [[NSUserDefaults standardUserDefaults] synchronize]

2) Try to find the string using -stringForKey:

+10
source

I recently encountered a similar problem. Here is what fixed it for me.

In iOS Application Programming Guide :

It is recommended that you register any default preference values ​​programmatically at startup, and include them in the property lists of the parameter list. For newly installed applications, default preferences from the set of application parameters are not set until the Settings application is launched. This means that if a user launches your application before launching the settings, the default values ​​specified in your parameter set will not be available. Setting these values ​​programmatically during startup ensures that your application always has the appropriate values. To programmatically register default values, use the registerDefaults: method of the NSUserDefaults class.

+7
source

What you should add:

 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"SavedCity"] != nil) 

Because you want to verify that you have saved something.

0
source

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


All Articles