2013-10-26 42 views
1

我創建了一個簡單的按鈕遊戲,每按一下按鈕,用戶就可以獲得一個點。該按鈕每1.5秒隨機出現在屏幕上。我希望遊戲在30秒後或20個隨機按鈕彈出窗口後結束。我一直在使用下面的代碼有按鈕隨機彈出屏幕上:如何在特定點停止NSTimer?

timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self 
     selector:@selector(moveButton:) 
     userInfo:nil 
     repeats:YES]; 

我已經聲明在頭文件中的計時器:

NSTimer *timer; 
@property (nonatomic, retain) NSTimer *timer; 

我讀過蘋果有關Using Timers的文檔,但未能完全理解它。我想也許我可以使用:

- (void)countedTimerFireMethod:(NSTimer *)timer{ 
    count ++; 
    if(count > 20){ 
    [self.timer invalidate]; 
    self.timer = nil; 

但它不能正常工作。我究竟做錯了什麼?我是Objective-C的新手,所以我不太熟悉事情的工作方式。

+0

計數聲明在哪裏?你有計算一個斷點,看看它是每個呼叫? –

+0

你能定義「不能正常工作」嗎?你看到你不想要的行爲是什麼? –

回答

3

的問題是在你的計時方法,你逝去的moveButton方法,但在下面的方法,你在哪裏停止計時器,方法名是不同的,所以試試這個: -

self.timer = [NSTimer  
    scheduledTimerWithTimeInterval: 1.5 target:self 
    selector:@selector(moveButton:) 
    userInfo:nil 
    repeats:YES]; 

//只是改變了方法名低於

- (void)moveButton:(NSTimer *)timer{ 
    count ++; 
    if(count > 20){ 
    [self.timer invalidate]; 
    self.timer = nil;} 
+0

要清楚,問題是傳遞給schedule方法的選擇器與下面的方法名稱不同。 –

+0

非常感謝!雖然這並沒有直接回答我的問題,但它確實使我得到了答案。 – Brian

+0

@Brian patino,你的歡迎:) –

0

如果您正在使用的Xcode的新版本,那麼你唐不需要聲明

NSTimer *timer; 

和調度計時器時,你可以使用

self.timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self 
     selector:@selector(moveButton:) 
     userInfo:nil 
     repeats:YES] 

,而不是

timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self 
     selector:@selector(moveButton:) 
     userInfo:nil 
     repeats:YES] 

您正在使用正確的方法停止計時器,即invalidate

您也可以參考link瞭解更多信息。

請讓我知道你是否通過上面的代碼解決了這個問題。