在尝试了多种方法在新线程中调用函数之后,只有以下代码适用于我
[NSThread detacNewThreadSelector:@selector(temp:) toTarget:self withObject:self];
以下不起作用:
NSThread *updateThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(temp:) object:self];
NSThread *updateThread1 = [[NSThread alloc] init];
[self performSelector:@selector(temp:) onThread:updateThread1 withObject:self waitUntilDone:YES];
现在,当我尝试拨打NSTimer
或在timer:
功能中执行选择器时,它不起作用查找下面的代码
int timeOutflag1 = 0;
-(void)connectCheckTimeOut
{
NSLog(@"timeout");
timeOutflag1 = 1;
}
-(void)temp:(id)selfptr
{
//[selfptr connectCheckTimeOut];
NSLog(@"temp");
//[NSTimer scheduledTimerWithTimeInterval:5 target:selfptr selector:@selector(connectCheckTimeOut) userInfo:nil repeats:NO];
[selfptr performSelector:@selector(connectCheckTimeOut) withObject:nil afterDelay:5];
}
- (IBAction)onUart:(id)sender {
protocolDemo1 *prtDemo = [[protocolDemo1 alloc] init];
//NSThread *updateThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(temp:) object:self];
//[self performSelector:@selector(temp:) onThread:updateThread1 withObject:self waitUntilDone:YES];
// [updateThread1 start];
[self performSelector:@selector(temp:) withObject:self afterDelay:0];
while(1)
{
NSLog(@"Whieloop");
if(timeOutflag1)
{
timeOutflag1 = 0;
break;
}
if([prtDemo isConnected])
break;
}
}
如果我使用[self performSelector:@selector(connectCheckTimeOut) withObject:nil afterDelay:5];
在onUart
函数中,它可以正常工作,我可以看到Timeout
printf
但在临时内部它不起作用。
答案 0 :(得分:1)
NSTimer
是基于运行循环的,所以如果你想在你自己产生和管理的后台线程上使用一个,你需要在该线程上启动一个runloop。阅读NSRunLoop
。简短版本可能类似于:
- (void)timedMethod
{
NSLog(@"Timer fired!");
}
- (void)threadMain
{
NSRunLoop* rl = [NSRunLoop currentRunLoop];
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(timedMethod) userInfo:nil repeats:YES];
[rl run];
}
- (void)spawnThread
{
[NSThread detachNewThreadSelector: @selector(threadMain) toTarget:self withObject:nil];
}