gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:04:11 25 4
gpt4 key购买 nike

我试图让 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com