IPhone SDK Default NSUserDefaults

后端 未结 3 1535
你的背包
你的背包 2021-01-15 10:32

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 the

相关标签:
3条回答
  • 2021-01-15 11:16

    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.

    0 讨论(0)
  • 2021-01-15 11:20

    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.

    0 讨论(0)
  • 2021-01-15 11:21

    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];
    
    0 讨论(0)
提交回复
热议问题