[英]IPhone SDK Default NSUserDefaults
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. 我已经设置用户默认为UISlider记录一个整数,问题是,如果用户仅安装了应用程序,则该整数为零或NULL。 Is there a way to detect if it = NULL with a integer?
有没有一种方法可以检测它是否为整数的NULL?
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. Senset是整数。 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. :(
我已经尝试过此代码,并且第一次将其设置为25,但是如果我尝试覆盖它,它将无法正常工作,并将其设置为25。:(
if ( [prefs integerForKey:@"senset"] == NULL ) {
senset = 25;
}
Please help :P 请帮忙:P
Harry 掠夺
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];
Just ask for objectForKey:. 只需询问objectForKey:。 If it isn't set, it will return nil.
如果未设置,它将返回nil。
Your test doesn't work, because integerForKey: with an unset value will return 0, which is nil, which is NULL. 您的测试不起作用,因为带有未设置值的integerForKey:将返回0,即nil,即NULL。 The differences between them only exist to the compiler.
它们之间的差异仅存在于编译器中。
If zero is not a valid value in a normal usage case (ie 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")? 编辑:错误,我想我有个问题:当您尝试覆盖它时,是否正在为密钥(@“ senset”)设置整数值(25)? 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.
如果不是,则它将保持为零或零,并且每次您检查它都会尝试将您的局部感知变量再次更改为25。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.