我遇到了一个问题
以下是代码
- (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];
}当我打电话的时候
[self performSelector:@selector(nlog) onThread:thread withObject:nil waitUntilDone:NO];线程将保持运行,稍后我可以在线程中执行某些操作;
但是如果我不调用它,线程将立即退出,并且永远不能使用该线程做任何事情,为什么?
发布于 2013-12-20 15:21:28
启动线程时,如果不向runloop添加任何源代码,run循环将立即返回。然后线程就结束了。
查看:
发布于 2013-08-18 15:35:45
首先,我不认为你对使用线程有正确的想法:
thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
[thread start];不要重写NSThread的“start”方法,应重写“main”方法。
其次,如果你想在线程中创建run循环,应该有一个while循环,如下所示:
while (condition)
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];顺便说一句,有关NSRunLoop:Best way to make NSRunLoop wait for a flag to be set?的更多详细用法,请参考我的回答
https://stackoverflow.com/questions/18272634
复制相似问题