2014-12-31 34 views
0

根據Run Loop的文檔如果有任何輸入源NSThread將運行,否則它將進入睡眠狀態。我配置了與上面鏈接中的「配置定時器源」下提供的定時器相同的定時器,但它沒有觸發。我使用下面的代碼。NSTimer從輔助NSThread不起作用

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    [NSThread detachNewThreadSelector:@selector(testOnThread) toTarget:self withObject:nil]; 
} 

- (void) testThread 
{ 

    NSLog(@"Test"); 
} 


-(void)testOnThread 
{ 
    @autoreleasepool { 

     NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop]; 

     // Create and schedule the first timer. 
     NSDate* futureDate = [NSDate dateWithTimeIntervalSinceNow:1.0]; 
     NSTimer* myTimer = [[NSTimer alloc] initWithFireDate:futureDate 
                interval:0.1 
                 target:self 
                selector:@selector(testThread) 
                userInfo:nil 
                repeats:YES]; 
     [myRunLoop addTimer:myTimer forMode:NSDefaultRunLoopMode]; 
    } 
} 

上面的代碼從不打印「測試」。

但是,如果我把[[NSRunLoop currentRunLoop] run];放在-(void)testOnThread方法的末尾,它會正常工作(Stackoverflow Question),但每次定時器都會觸發。我的查詢是,如果我們已經提供了定時器輸入源運行環比什麼是需要使用[[NSRunLoop currentRunLoop] run];

+0

做'run'鎖定線程進入運行循環,直到循環排出,防止螺紋從計時器到期之前立即退出並刪除運行循環。 –

回答

1

我讓別人回答你爲什麼要run問題的runloop自己明確啓動它。但我想建議一個替代方案:

如果你想在後臺線程上運行定時器,使用調度定時器是最簡單的,恕我直言,沒有runloop需要。只要定義定時器屬性:

@property (nonatomic, strong) dispatch_source_t timer; 

,然後安排計時器上的自定義隊列中運行:

dispatch_queue_t queue = dispatch_queue_create("com.domain.app.timer", 0); 
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); 
dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), 20ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC); 

dispatch_source_set_event_handler(timer, ^{ 
    // code to be performed periodically on background thread here 
}); 

dispatch_resume(self.timer); 
+0

我使用NSThread,因爲我的Mac支持OS X 10.4及更高版本。我不能在那裏使用GCD –