2012-03-30 24 views
0

非常簡單的使用NSThread和NSTimer,如下所示。當用戶點擊一個按鈕時,我希望每秒打印@「aaaaa」,但@「aaaaa」只打印一次?似乎NSTimer不起作用...幫助NSTimer不能在NSThread中工作?

//this method is connected to 'run' button in IB 
- (IBAction)begin1:(id)sender { 
    [NSThread detachNewThreadSelector:@selector(thread1) toTarget:self withObject:nil]; 
} 

-(void)thread1{ 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 
                 target:self 
                selector:@selector(aaa) 
                userInfo:nil 
                repeats:YES]; 
    [timer fire]; 
} 

-(void)aaa{ 
    NSLog(@"aaaaa"); 
} 

回答

0

您沒有保留計時器。 + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats返回一個自動發佈的NSTimer,所以如果你想確保它運行,直到你告訴它停止,你應該保留它。

+0

謝謝。似乎我也錯過了創建NSTimer的'NSRunLoop'。 – 2012-03-30 03:15:42

+0

他爲什麼需要保留它?他不使用它在另一個功能,它應該是可行的。或者你使用ARC? – Gargo 2012-03-30 04:42:59

0

對於運行循環,定時器不是有效的源,它將保持運行。據推測,你的運行循環認爲它沒有任何可做的事情,然後退出,使其計時器失效 - 如果你的實際實現是寫入的,那將是這種情況。因此,您需要確保輔助線程的運行循環繼續,以便定時器繼續觸發,因爲線程剛剛退出並將定時器與現在一起使用。