Lolloz89
Lolloz89

Reputation: 2809

Problems in loading from NSUserDefaults

I have a very strange problem while my app loads from NSUserDefaults. This is the code in my appDelegate:

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 NSString *user = [[NSString alloc]initWithString:[defaults objectForKey:@"_settingsUsername"]];
 NSString *password = [[NSString alloc]initWithString:[defaults objectForKey:@"_settingsPassword"]];
 NSString *instance = [[NSString alloc]initWithString:[defaults objectForKey:@"_settingsInstance"]];

The error is this: [NSPlaceholderString initWithString:]: nil argument' It's very strange because i put in Settings.bundle -> Root.plist the default values for all the fields above.

Upvotes: 1

Views: 226

Answers (3)

Novarg
Novarg

Reputation: 7450

Why don't you just use that?

NSUserDefaults *defaults = [NSUserDefaults standarduserDefaults];
NSString *user = [defaults objectForKey:@"_settingsUsername"];
NSString *password = [defaults objectForKey:@"_settingsPassword"];
NSString *instance = [defaults objectForKey:@"_settingsInstance"];

And make sure that there are objects for these keys.

hope it helps

Upvotes: 1

Stephen Darlington
Stephen Darlington

Reputation: 52575

Oddly that's how it's supposed to work -- this confused me too initially.

I guess the thing to remember is that you can use NSUserDefaults without the Settings.bundle, so it can't be the only way to set default values.

Apple provide sample code, AppPrefs, that shows how to copy the default value from the settings to NSUserDefaults.

Upvotes: 1

mattjgalloway
mattjgalloway

Reputation: 34912

I think the problem is that if the user hasn't gone into the settings for your app yet then all values returned from NSUserDefaults for those keys are nil. You need to handle that case and act accordingly - probably by going into the Settings.bundle and picking out the default value that you have put in there. I would just write a method that gets the value for a key and if NSUserDefaults returns nil it handles all the querying of the settings bundle for you.

Upvotes: 0

Related Questions