standardUserDefaults reading problem
I've got a problem similar to link text
I'm using XCode 3.2.4 (1708). After I reinstalled it, I'm started to get Nil from my NSUserDefaults object.
If I'm writing:
- (void)viewDidLoad {
NSUserDefaults *sUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *myAdd = [standardUserDefaults objectForKey:kMyIPaddress];
}
I get Nil in myAdd variable, but if I do like that:
- (void)viewDidLoad {
NSUserDefaults *sUserDefaults = [NSUserDefaults standardUserDefaults];
[standa开发者_如何学运维rdUserDefaults setObject:@"192.168.1.2" forKey:kMyIPaddress];
NSString *myAdd = [standardUserDefaults objectForKey:kMyIPaddress];
}
I get 192.168.1.2 in myAdd object. So looks like UserDefaults stays empty before I put something to them, but they exists in General Preferences and contains proper values. Why can't I access them before I put something there?
You need to register your default values with NSUserDefaults.
NSDictionary *def = [NSDictionary dictionaryWithObjectsAndKeys:
@"192.168.1.2", kMyIPaddress,
nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:def];
and you need to do this every time your app starts.
It doesn't matter that there are settings in the Settings.app (my interpretation of your General Preferences
). If those values are not changed manually they are not stored in NSUserDefaults.
Did you do a
[[NSUserDefaults standardUserDefaults] synchronize];
after putting your NSString there?
精彩评论