1

在尝试了多种方法在新线程中调用函数之后,只有下面的代码对我有用

[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但在 temp 内部它不起作用。

4

1 回答 1

1

NSTimer是基于运行循环的,所以如果你想在你自己产生和管理的后台线程上使用一个,你需要在那个线程上启动一个运行循环。继续阅读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];
}
于 2013-09-16T11:51:02.163 回答