IPhone SDK default NSUserDefaults

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

Here is my code that I have:

-(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 an integer. I tried this code and it sets it to 25 the first time, but if I try to overwrite it it doesn't work and sets it to 25 .:(

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

      

Please help: P

Harry

+2


source to share


3 answers


You must set a valid default for each of your preferences. This value will be used if the user was not set by the user.



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

      

+4


source


Just ask for objectForKey :. If not set, it will return zero.



Your test is not working because integerForKey: with an unspecified value will return 0, which is zero, which is NULL. The differences between them exist only for the compiler.

+1


source


If zero is not a valid value in normal use case (i.e. your stored preference will never set that integer to zero), 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 giving an integer value (25) for your key (@ "senset")? If not, then it will remain null or null and every time you check it, it will try to change your local sensitivity variable to 25 again.

+1


source







All Articles