NSUserDefaults not working right

2020-02-14 06:12发布

Having some trouble with NSUserDefaults here.

Here's how I'm creating it:

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

Here's how I'm trying to retrieve it:

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

The problem I have 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!

3条回答
放我归山
2楼-- · 2020-02-14 06:20

What you should add is:

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

Because you want to check if you've saved something.

查看更多
别忘想泡老子
3楼-- · 2020-02-14 06:28

I ran into a similar problem myself recently. Here's what fixed it for me.

From the iOS Application Programming Guide:

It is recommended that you register any default preference values programmatically at launch time in addition to including them in your settings bundle property lists. For newly installed applications, default preference values from the application’s settings bundle are not set until the Settings application runs. This means that if the user runs your application before running Settings, the default values specified in your settings bundle will not be available. Setting such values programmatically at launch time ensures that your application always has appropriate values. To register default values programmatically, use the registerDefaults: method of the NSUserDefaults class.

查看更多
可以哭但决不认输i
4楼-- · 2020-02-14 06:45

Two things you could try.

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

2) Try retrieving the string using -stringForKey:

查看更多
登录 后发表回答