ios - 新线程的问题

标签 ios objective-c multithreading nsthread

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

[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 中它不起作用。

最佳答案

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];
}

关于ios - 新线程的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18826929/

相关文章:

ios - 转换为 ARC——解析前向引用

java - Java 的 LockSupport.parknanos 的 .NET 等价物是什么?

c# - INotifyPropertyChanged 绑定(bind)和跨线程错误

multithreading - 先发制人如何运作?

objective-c - UITableView 之上的自定义手势

objective-c - 拆分一个大的 UIImage 以供纹理使用

iphone - 适用于 Windows 平台上 iOS 开发的 Titanium

ios - 奇怪的 NSURLSessionDownloadTask 行为通过蜂窝(不是 wifi)

ios - 将文件从 iOS 11 Files 应用程序复制到沙箱

ios - 在后台下载/上传完成后,使用后台任务处理额外的 HTTP 请求是否是一种正确的方法?