2012-02-19 62 views
5

對於我的生活,我無法弄清楚爲什麼這個NSTimer不會射擊。這裏是所有出現相關的代碼(至少對我來說)NSTimer沒有射擊

- (IBAction)connectClick:(id)sender 
{ 
    if (connected) 
    { 
     NSLog(@"Disconnecting"); 
     [timer invalidate]; 
     timer = nil; 
     connected = NO; 
     [Connect setStringValue:@"Connect"]; 
     NSLog(@"Finished\n"); 
    } 
    else 
    { 
     NSLog(@"Connecting"); 
     timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES]; 
     //[timer fire]; tested this line. same results 
     [Connect setStringValue:@"a"]; 
     connected = YES; 
     NSLog(@"Finished\n"); 
    } 
} 

- (void)timerFireMethod:(NSTimer*)theTimer 
{ 
    NSLog(@"Fireing event"); 
    //[self resetRequest]; 
    //[spinner startAnimation:nil]; 
    //[request startAsynchronous]; 
} 

我已閱讀蘋果文檔,以及其他問題,但我不能弄明白。它甚至不叫timerDireMethod:一次。我聽說這可能是由不同的線程引起的,但據我所知,我沒有使用多線程。

歡迎任何想法。

+0

的[的NSTimer不費一槍]可能重複(http://stackoverflow.com/questions/6752234/nstimer-not-firing) – Caleb 2012-02-19 05:59:19

+0

是否有某種原因,你用NSEventTrackingRunLoopMode代替NSDefaultRunLoopMode? – Caleb 2012-02-19 06:06:52

+0

對不起在這裏晚了。我只是注意到了這一點,並打算在這個問題上加上這一點。但是是NSDefaultRunLoopMode工作。抱歉讓你困惑。 – 2012-02-19 06:07:53

回答

9

NSTimer documentation爲Mac OS X:

您必須將新的計時器添加到運行循環,使用addTimer:forMode :. 然後,經過幾秒鐘後,定時器將觸發,併發送消息aSelector作爲目標。 (如果計時器被配置爲重複, 沒有必要隨後計時器重新添加到運行循環。)

就個人而言,我通常使用+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]

還要注意的是,如果你把這個方法在後臺線程上運行,或者在後臺隊列中運行的塊操作中,NSTimer在後臺線程執行時被破壞。所以請確保您在主線程或主隊列中運行它,如果適合您的情況。

+1

+1偉大的思想家都認爲一樣。 ;-) – Caleb 2012-02-19 06:04:16

+0

哈,很好的團隊合作! – bneely 2012-02-19 06:11:39

+0

我用這個,但它仍然沒有射擊。 – shim 2013-07-17 04:49:31

1

閱讀您所使用的方法的文檔,+timerWithTimeInterval:target:selector:userInfo:repeats:

您必須添加新的計時器的運行循環,使用addTimer:forMode :. 然後,經過幾秒鐘後,定時器將觸發,併發送消息aSelector作爲目標。

+1

+1偉大的思想家都一樣。 ;-) – bneely 2013-05-23 21:43:45