首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >线程中的NSRunloop

线程中的NSRunloop
EN

Stack Overflow用户
提问于 2013-08-16 19:49:05
回答 2查看 1.9K关注 0票数 0

我遇到了一个问题

以下是代码

代码语言:javascript
复制
- (void)start{
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}

- (void)nlog{
    NSLog(@"cool");
}


- (void)main{



    thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];

    [thread start];


    [self performSelector:@selector(nlog) onThread:thread withObject:nil waitUntilDone:NO];
}

当我打电话的时候

代码语言:javascript
复制
[self performSelector:@selector(nlog) onThread:thread withObject:nil waitUntilDone:NO];

线程将保持运行,稍后我可以在线程中执行某些操作;

但是如果我不调用它,线程将立即退出,并且永远不能使用该线程做任何事情,为什么?

EN

回答 2

Stack Overflow用户

发布于 2013-12-20 15:21:28

启动线程时,如果不向runloop添加任何源代码,run循环将立即返回。然后线程就结束了。

查看:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1

票数 0
EN

Stack Overflow用户

发布于 2013-08-18 15:35:45

首先,我不认为你对使用线程有正确的想法:

代码语言:javascript
复制
thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];

[thread start];

不要重写NSThread的“start”方法,应重写“main”方法。

其次,如果你想在线程中创建run循环,应该有一个while循环,如下所示:

代码语言:javascript
复制
while (condition)
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];

顺便说一句,有关NSRunLoop:Best way to make NSRunLoop wait for a flag to be set?的更多详细用法,请参考我的回答

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18272634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档