-5

我刚刚观看了有关如何设置默认值的教程,并且想知道将默认值的值输出到文本。我的问题是:我可以在 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);

但它没有用。它说“使用未声明的标识符'defaults'”和“expected expression”我尝试将代码移动到'defaults'声明的下方,但这没有任何区别。希望有人能回复!

4

2 回答 2

2

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

于 2013-07-10T00:43:38.357 回答
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以前没有被声明和实例化。最后,我假设您正在寻找一个与字符串键“kMusic”一起存储的布尔值,因此在代码的其他地方您使用类似的东西[[NSUserDefaults standardUserDefaults] setBool:true forKey:@"kMusic"]; 如果这不是您的想法,您将需要进行更改因此。

最后,下一次,在将代码带到 Stack Overflow 之前,重新阅读您的代码是否存在拼写错误。

于 2013-07-10T01:09:52.250 回答