2014-06-13 22 views
0

我有一個提醒,顯示第一次啓動應用程序,要求用戶的權限允許應用程序發送本地通知。我在AppDelegate.m。警報是好的,但是我在代碼中有一個錯誤來測試哪個按鈕被按下(是或否)。詢問用戶的權限使用本地通知

我在- (void)alertView:clickedButtonAtIndex:行發生錯誤,說使用未聲明的標識符alertview

下面的代碼:

//ask user if its ok to send local notifications 
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Notifications?" 
                message:@"Is it ok for this app to send you reminder notifications? (You can change this in Settings)" 
               delegate:self 
             cancelButtonTitle:@"No" 
             otherButtonTitles:@"Yes", nil]; 
[message show]; 

//which button was clicked? 
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    NSString *title = [UIAlertView buttonTitleAtIndex:buttonIndex]; 
    if([title isEqualToString:@"No"]) 
    { 
     NSLog(@"NO was selected."); 
     [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"notifications"]; //0 = off, 1 = on 
    } 
    else 
    { 
     NSLog(@"YES was selected."); 
     [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"notifications"]; //0 = off, 1 = on 
    }  
} 

回答

2

更換行:

NSString *title = [UIAlertView buttonTitleAtIndex:buttonIndex]; 

有:

NSString *title = [alertView buttonTitleAtIndex:buttonIndex]; 

UIAlertView類沒有類方法buttonTitleAtIndex:。這是一個實例方法應該在UIAlertView類的實例上調用。

如果您想要使用alertView:clickedButtonAtIndex:方法,請確保您符合UIAlertViewDelegate協議。

編輯

像@Sam建議你還可以利用buttonIndex代替按鈕title,它可以在未來改變讓你有一個錯誤,如果你不更新if語句。

if (buttonIndex == 1) { 
    // do something 
} else { 
    // do something else 
} 

編輯2

確保你有一個右括號 「}」 之前的方法定義。

- (void)someMethod 
{ 
    ... 
} <= DONT FORGET TO TYPE A CLOSING BRACKET 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
{ 
    ... 
} 
+1

你可能不需要做字符串比較要麼...索引一個簡單的檢查標準。我認爲在這裏0 ==沒有,1 ==是嗎? –

+0

你不需要,我可能會做略微不同,但如果他決定改變這些按鈕的順序,它會打破,如果他引用索引,而這將仍然按照設計,如果他改變是和NO到NO和YES。 – Mike

+0

好的,非常感謝你的建議。我的問題是UIAlertViewDelegate協議。上面的代碼在appdelegate.m文件中調用 - 不是視圖控制器文件 - 所以我還沒有使用協議 - 毫無疑問,這是我的問題。但我應該如何使用它?我在錯誤的文件中,我想知道?我可以在appDelegate中做到這一點嗎? – ianM