IPhone SDK Default NSUserDefaults

隐身守侯 提交于 2019-12-01 07:24:47

问题


I have set up the user defaults to record a integer for a UISlider, the problem is that, if the user has only just installed the app then the integer is zero or NULL. Is there a way to detect if it = NULL with a integer?

heres my code i have so far:

-(void)awakeFromNib {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
senset = [prefs integerForKey:@"senset"];
senset = sensitivity.value;
}
- (IBAction) setSens {
senset = sensitivity.value;
}
- (IBAction) goBackopt {
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setInteger:senset  forKey:@"senset"];
    [prefs synchronize];
}

 }

senset is the integer. i have tried this code, and it sets it to 25 on the first time, but then if i try and overwrite it, it wont work and keeps setting it to 25. :(

    if ( [prefs integerForKey:@"senset"] == NULL ) {
    senset = 25;    
}

Please help :P

Harry


回答1:


You should set a valid default value for each of your preferences. This value will be used when one has not been set by the user.

NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
[defaults setObject:[NSNumber numberWithInt:25] forKey:@"senset"];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];



回答2:


Just ask for objectForKey:. If it isn't set, it will return nil.

Your test doesn't work, because integerForKey: with an unset value will return 0, which is nil, which is NULL. The differences between them only exist to the compiler.




回答3:


If zero is not a valid value in a normal usage case (i.e. your saved preference would never set this integer to zero), then you can check

if( [prefs integerForKey:@"senset"] == 0){
    [prefs setInteger:25 forKey:@"senset"];
}

Edit: err, I suppose I have a question: when you try to overwrite it, are you setting an integer value(25) for your key (@"senset")? If not, then it will remain zero or nil, and everytime you check it will attempt to change your local senset variable to 25 again.



来源:https://stackoverflow.com/questions/2614468/iphone-sdk-default-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!