告诉程序找不到保存数据时该怎么办NSUserDefaults,iPhone [英] Tell The Program What To Do When No Save Data Is Found NSUserDefaults, iPhone

查看:152
本文介绍了告诉程序找不到保存数据时该怎么办NSUserDefaults,iPhone的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经保存了使用NSUserDefaults保存的数据.我给人的印象是,如果已经没有任何内容保存到密钥中(第一次运行应用程序),它将默认为0.但是,情况似乎并非如此.

I have saved data which was saved using NSUserDefaults. I was under the impression that if there was nothing saved to the key already (first time app is run) it would default to 0. This however doesn't seem to be the case.

这就是我所拥有的:

要保存:

- (void)viewWillDisappear:(BOOL)animated
{
[[NSUserDefaults standardUserDefaults] setInteger:setbatteryHealthCalculated     forKey:@"healthValue"];

    [[NSUserDefaults standardUserDefaults] synchronize];

}

要加载:

- (void) viewWillAppear:(BOOL)animated
{
NSInteger setbatteryHealthCalculated = [[NSUserDefaults standardUserDefaults]     integerForKey:@"healthValue"];
}

要检查保存值:

- (IBAction)check{

    NSInteger setbatteryHealthCalculated = [[NSUserDefaults standardUserDefaults] integerForKey:@"healthValue"];


    if  (setbatteryHealthCalculated = 0) {

                [self performSelector:@selector(displayAlert) withObject:nil];

}
}

推荐答案

if  (setbatteryHealthCalculated = 0) {

嗯.应该是

if  (setbatteryHealthCalculated == 0)


在类似C的语言中,比较运算符为==而不是=.


The comparison operator is == instead of = in C-like languages.

无论如何,原始代码都会将setbatteryHealthCalculated设置为0.由于0为假,因此if分支将永远不会执行,也不会显示任何警报.

The original code will set setbatteryHealthCalculated to 0 no matter what. Since 0 is false, the if branch will never be executed and no alerts would be shown.

此外,原始代码的花括号不平衡.

Also, the original code has unbalanced braces.

顺便说一句,setbatteryHealthCalculated是一个ivar吗?如果是,请在其之前删除NSInteger.否则,您将声明一个遮盖ivar的局部变量.

BTW, is setbatteryHealthCalculated an ivar? If yes, remove the NSInteger before it. Otherwise you're declaring a local variable which shadows the ivar.

这篇关于告诉程序找不到保存数据时该怎么办NSUserDefaults,iPhone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆