保持对NSThread的引用并发送其对象的消息?

时间:2010-04-27 10:01:37

标签: cocoa nsthread

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

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

[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类中的所有任务目前仅依赖于时间。我想有一些“事件依赖”。例如我想从我的主线程中调用Background对象并告诉它“speedUp”,“slowDown”,“reset”或对象上的任何方法。

要做到这一点,我想我需要像performSelectorOnThread这样的东西,但是如何获得对NSthread和背景对象的引用?

1 个答案:

答案 0 :(得分:3)

直接回答:使用[[NSThread alloc] initWithTarget:selector:object:]而不是+ [NSThread detachNewThreadSelector:toTarget:withObject:]。别忘了打电话给-start!

其他想法:

  • 请考虑使用NSOperation / NSOperationQueue。大多数工作线程使用更容易,更有效。
  • 考虑您是否真的需要对后台线程进行定期检查。你可以在主运行循环中执行它,然后根据需要将工作抛到其他线程上吗?线程不是免费的。
  • 考虑轮询是否也是最佳实施方式。查看NSCondition和/或NSConditionLock以获得更有效的方法来在发生某些事情时唤醒线程(比如将工作添加到队列中),不需要轮询。