2010-01-19 34 views
1

我在代碼中注意到,當我嘗試從輔助線程啓動NSTimer時,它不起作用。我試着調用+ [NSRunLoop currentRunLoop],以防萬一問題是線程沒有運行循環...但沒有骰子。 (請注意,這是在黑暗中拍攝的,文檔說會創建一個運行循環,但也許還有其他配置,我需要做,但沒有。)從輔助線程啓動NSTimer時出現的問題

我知道調用像 - [NSObject performSelectorOnMainThread:]這可以解決我的問題(實際上,我的解決方案是簡單地將此代碼移動到主線程,這可以正常工作),但我仍然對爲什麼會出現此問題感到好奇。從輔助線程啓動NSTimer實際上是不可能的嗎?有沒有解決方法?

非常感謝。

+0

謝謝大家...直到今天晚些時候,我纔會有時間嘗試它,但我不認爲我正確地開始運行循環。 –

+0

是的,的確,這是問題所在:我沒有調用[runLoop run]。謝謝您的幫助。 –

回答

0

確保你A)將計時器添加到當前runloop,並B)運行所述runloop。當您的計時器觸發時,如果您想退出[runloop run]調用,請調用[runloop stop]。當你調用該方法

scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:

它會自動安排對當前NSRunLoop計時器

2

以下代碼段適用於我。

-(id)init { 
    myWorkerThread = [[NSThread alloc]initWithTarget:self selector:@selector(workerThread) object:nil]; 
    [myWorkerThread start]; 
} 

#pragma mark WorkerThread Support 
-(void)stillWorking { 
    NSLog(@"Still working..."); 
} 

-(void)workerThread { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 
    NSTimer *threadTimer = [NSTimer scheduledTimerWithTimeInterval:10 
           target:self 
           selector:@selector(stillWorking) 
           userInfo:nil 
           repeats:YES]; 

    [[NSRunLoop currentRunLoop] addTimer:threadTimer forMode:NSDefaultRunLoopMode]; 
    [[NSRunLoop currentRunLoop] run]; 

    [pool drain]; 
} 
1

約翰·富蘭克林的回答是correct..but。因此,您不需要再將計時器添加到當前運行循環中,只能調用[[NSRunLoop currentRunLoop] run]方法。