2013-07-10 18 views
-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); 

但它沒有奏效。它說「使用undeclaired標識符'默認值''和'預期表達式'我試着將代碼移到'默認值'聲明之下,但沒有任何區別。我希望有人能回覆!

+2

顯示默認值的聲明和初始化。 – Gary

+1

該代碼看起來不像它將編譯。 –

+5

請在使用Objective-C嘗試更多東西之前,先學習如何編程。從C或Java開始。 –

回答

2

將用戶默認值存儲在userDefaults中上述代碼有許多問題。首先,讓我指出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"];的東西如果這不符合你的想法,你需要相應地改變。

最後,下一次,重新讀取您的錯誤代碼,然後將其帶入堆棧溢出。

+0

下面是蘋果文檔的鏈接,您應該在繼續之前閱讀這些鏈接:http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/UserDefaults/Introduction/Introduction.html「首選項和設置編程指南」 – KHansenSF

2

將缺省值替換爲[NSUserDefaults standardUserDefaults]。但是如果你要求返回一個字符串,你不能將它與布爾值進行比較。但是您可以使用setBool:forKey:boolForKey:

+0

謝謝@KHansenSF!我試圖嘗試,但我不完全知道如何將它放在代碼中。這是我失敗的嘗試:if([[NSUserDefaults standardUserDefaults] stringForKey:kMusic])== YES { CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef soundFileURLRef; (CFBtringRef)@「click」,CFSTR(「wav」),NULL); UInt32 soundID; AudioServicesCreateSystemSoundID(soundFileURLRef,&soundID); AudioServicesPlaySystemSound(soundID); – George523

+1

如果你想添加代碼,請編輯這個問題,沒有人想要閱讀評論中的混亂。 – WolfLink