【发布时间】:2013-05-10 07:45:20
【问题描述】:
我读过很多关于NSRunLoop 的帖子,比如this、this、this。但是不知道NSRunLoop到底做了什么
平时看到的是工作线程
wthread = [[NSThread alloc] initWithTarget:self selector:@selector(threadProc) object:nil];
[wthread start];
里面有一个 NSRunLoop
- (void)threadProc
{
NSAutoreleasePool* pool1 = [[NSAutoreleasePool alloc] init];
BOOL isStopped = NO;
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
[runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
while (!isStopped)
{
{
NSAutoreleasePool* pool2 = [[NSAutoreleasePool alloc] init];
[runloop runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]];
[pool2 release];
}
}
[pool1 release];
}
主线程将一些工作传递给这个 wthread
[self performSelector:@selector(someWork:) onThread:wthread withObject:nil waitUntilDone:NO];
在将工作从主线程传递到工作线程方面,我看到很多人这样做。为什么这里需要 NSRunLoop ?它有什么作用?
我读到NSRunLoop是用来管理事件的,为什么除了在threadProc里面调用runMode之外什么都没有?
【问题讨论】:
-
我认为它是一个花哨的 while(true){ //insert job to be done here } ,您可以在其中动态添加要执行的代码(事件、工作、套接字等)。 runloop 并不是真正的空,一个端口已经附加到 runloop,它是一种进程间通信的形式。
-
我发现这个bou.io/RunRunLoopRun.html 也很有用
标签: ios port nsthread nsrunloop