1

我有点不确定如何做到这一点:

我启动了一个在我的应用程序“生命”期间运行的“工作线程”。

[NSThread detachNewThreadSelector:@selector(updateModel) toTarget:self withObject:nil];

然后

- (void) updateModel {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    BackgroundUpdate *update = [[BackgroundUpdate alloc] initWithTimerInterval:5];
    [[NSRunLoop currentRunLoop] run];   //keeps it going 'forever'
    [update release];
    [pool release];
}

现在线程每 5 秒“唤醒”一次(initWithTimerInterval)以查看它是否可以执行任何任务。BackGroundUpdate 类中的所有任务现在只是时间相关的。我想要一些“事件相关”的。例如,我想从我的主线程调用背景对象并告诉它“speedUp”、“slowDown”、“reset”或对象上的任何方法。

为此,我想我需要类似performSelectorOnThread但如何获取对 NSthread 和背景对象的引用?

4

1 回答 1

3

直接回答:不要使用+[NSThread detachNewThreadSelector:toTarget:withObject:],而是使用[[NSThread alloc] initWithTarget:selector:object:]。不要忘记调用 -start!

其他想法:

  • 考虑改用 NSOperation/NSOperationQueue。对于大多数工作线程使用来说更容易、更高效。
  • 考虑您是否真的需要在后台线程上进行定期检查。你可以在主运行循环上做,然后根据需要把工作交给其他线程吗?线程不是免费的。
  • 考虑轮询是否也是最好的实现。查看 NSCondition 和/或 NSConditionLock 以获得更有效的方法来在发生某些事情时唤醒线程(例如将工作添加到队列中),而无需轮询。
于 2010-06-24T00:20:23.813 回答