objective-c - NSTimer 未在子线程中触发

标签 objective-c ios nstimer nsthread

我试图让 NSTimer 在子线程中触发。我的代码基本上是这样的:

-(void) handleTimer:(NSTimer *)theTimer {  
    NSLog(@"timer fired");  
}

-(void) startMyThread {  
    // If I put timer in here, right before I start my new thread, it fires.  
    // [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:NO];  
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];  
}

// This method is called from inside the new thread  
-(void) playNote:(Note *)theNote withTemplate:(NSString *)theTemplate X:(int)x andY:(int)y {
    NSLog(@"before timer");  
    // The timer doesn't fire in here. (But the print statements do.)  
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:NO];
    NSLog(@"after timer");  
}

我真的很想(阅读:需要?)在子线程中触发计时器,因为它将用于停止播放音符(并且所有音符播放都需要在子线程中进行)。

关于 NSTimer 如何在子线程中运行,我一定是遗漏了一些东西...
过早感谢您的帮助!

最佳答案

除非在运行循环中安排,否则计时器不会触发。您还需要避免随意增加线程。

除非您的 run 方法启动运行循环,否则您的计时器不会触发。

顺便说一句,更好的解决方案可能是使用 GCD 的 dispatch_after()。它比线程更轻,但这取决于您需要做什么。不过,一般来说,队列是向应用程序添加并发性的更有效方法。


从评论中抓取代码以正确格式化(很好的发现):

double delayInSeconds = .2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    NSLog(@"dispatch popped");
});

一个补充说明;您可能会考虑使用全局并发队列之一。当主事件循环可能阻塞时,它们不会阻塞。当然,如果您要更新 UI,无论如何都必须返回 MEL。

关于objective-c - NSTimer 未在子线程中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11573843/

相关文章:

iphone - 使用特定长度的随机字节生成 NSData 对象的最佳方法?

ios - 如何将 NSPredicate 与多维数组一起使用(其中 predicateFormat 存在于 valueForKeyPath 中)

ios - 无法更改 WKWebView 中 UIScrollview 的内容大小

cocoa-touch - 是否可以使用 NSTimer 和 UIDatepicker 来发出警报?

ios - 如何在 iOS/Objective C 中 DRY 代码?

objective-c - 关闭 AlertView 时显示新 View

ios - "Cannot load NSManagedObjectModel. nil is an illegal URL parameter"

xcode - 执行某项操作 "x"秒,然后执行其他操作

ios - NSTimer 类方法和失效

ios - 从另一个 ViewController 捕获屏幕截图 - Obj C