Objective c 使NSThread保持活动状态并在其上运行nsrunlop

Objective c 使NSThread保持活动状态并在其上运行nsrunlop,objective-c,cocoa,nsthread,foundation,nsrunloop,Objective C,Cocoa,Nsthread,Foundation,Nsrunloop,因此,我正在启动一个新的NSThread,我希望以后能够通过调用performSelector:onThread:…来使用它。从我对调用方法的理解来看,方法将该调用添加到该线程的runloop中,因此在下一次迭代中,它将弹出所有这些调用,并随后调用它们,直到没有剩余的调用为止。所以我需要这种功能,一个空闲线程,可以随时工作,我可以调用它。我当前的代码如下所示: - (void)doInitialize { mThread = [[NSThread alloc] ini

因此,我正在启动一个新的NSThread,我希望以后能够通过调用
performSelector:onThread:…
来使用它。从我对调用方法的理解来看,方法将该调用添加到该线程的runloop中,因此在下一次迭代中,它将弹出所有这些调用,并随后调用它们,直到没有剩余的调用为止。所以我需要这种功能,一个空闲线程,可以随时工作,我可以调用它。我当前的代码如下所示:

   - (void)doInitialize
   {
       mThread =  [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];
       [mthread start];
   }

   - (void)runThread
   {
       NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];

       // From what I understand from the Google machine is that this call should start the
       // runloop on this thread, but it DOESN'T. The thread dies and is un-callable
       [[NSRunLoop currentRunLoop] run];

       [pool drain];
   }

   - (void)scheduleSomethingOnThread
   {
       [self performSelector:@selector(hardWork) onThread:mThread withObject:nil waitUntilDone:NO];
   }

但是线程没有保持活动状态,并且performSelector:onThread不做任何事情。如何以正确的方式进行此操作?

运行循环至少需要一个“输入源”才能运行。主运行循环确实如此,但您必须手动添加源,以获得辅助运行循环的
-run
方法来执行任何操作。这方面有一些文件

一种简单的方法是将
[[nsrunlop currentlunloop]run]
放入无限循环中;当有事情要做时,它会去做,否则它会立即返回。问题是,线程仅仅等待某些事情发生就需要相当长的处理器时间

另一个解决方案是在这个运行循环上安装一个NSTimer,以使其保持活动状态


但是,如果可能的话,你应该使用为这种事情设计的机制。如果可能,您可能希望使用
NSOperationQueue
进行后台操作

这段代码应该强制线程永远等待

BOOL shouldKeepRunning = YES;        // global
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; // adding some input source, that is required for runLoop to runing
while (shouldKeepRunning && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); // starting infinite loop which can be stopped by changing the shouldKeepRunning's value

命令行工具中的主运行循环也是如此。是NS/UIApplication在GUI应用程序的主运行循环上提供默认输入源。