根據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];
做'run'鎖定線程進入運行循環,直到循環排出,防止螺紋從計時器到期之前立即退出並刪除運行循環。 –