使用If默认语句?

时间:2013-07-10 00:38:13

标签: iphone objective-c if-statement

我刚看了一个关于如何设置默认值的教程,并且想知道如何将默认值输出到文本。我的问题是:我可以在if语句中使用默认值。我试过这个:

-(IBAction)press {
cruzia.hidden = 0;
textarea.hidden = 0;
if ([defaults stringForKey:kMusic]) == YES {
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"click", CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

但它没有用。它说“使用未声明的标识符'默认值'”和“预期表达式”我尝试将代码移动到“默认值”声明之下,但这没有任何区别。我希望有人能回复!

2 个答案:

答案 0 :(得分:2)

将默认值替换为[NSUserDefaults standardUserDefaults]。但是如果要求返回一个字符串,则无法将其与布尔值进行比较。但您可以使用setBool:forKey:boolForKey:

将booleans存储在userDefaults中

答案 1 :(得分:2)

上述代码存在许多问题。首先,我要指出,if语句和函数都没有右括号。然后,== YES在括号之外。接下来,您尝试将NSString的实例与布尔值进行比较。最后,defaultskMusic都没有被声明。

所以这里有一些固定的代码:

-(IBAction)press {
cruzia.hidden = 0;
textarea.hidden = 0;

defaults = [NSUserDefaults standardUserDefaults];
//if defaults has been instantiated earlier and it is a class variable, this won't be necessary.
//Otherwise, this is part of the undeclared identifier problem



/*the other part of the undeclared identifier problem is that kMusic was not declared.
I assume you mean an NSString instance with the text "kMusic", which is how I have modified the below code.
If kMusic is the name of an instance of NSString that contains the text for the key, then that is different.

also, the ==YES was outside of the parentheses.
Moving that in the parentheses should fix the expected expression problem*/
if ([defaults boolForKey:@"kMusic"] == YES) {

    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"click", CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
    }
}

现在,在您复制并过去替换旧代码之前,您应该了解我所做的假设。我假设defaults先前已声明并实例化 not 。最后,我假设你正在寻找一个用字符串键“kMusic”存储的布尔值,所以你的代码中的其他地方你使用类似[[NSUserDefaults standardUserDefaults] setBool:true forKey:@"kMusic"];的东西。如果这不是你的想法,那么你将需要相应地进行更改。

最后,下次重新编写拼写错误的代码,然后再将其转换为Stack Overflow。