码迷,mamicode.com
首页 > 编程语言 > 详细

OC原理之多线程(二)

时间:2021-02-24 13:19:34      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:fir   invalid   kvo   val   first   mod   uncaught   The   代码   

对于如下代码的,它的打印结果是什么

NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"1");
    }];
    [thread start];
    [self performSelector:@selector(testhaha) onThread:thread withObject:nil waitUntilDone:true];

- (void)testhaha {
    NSLog(@"2");
}

运行之后打印结果如下:

2021-02-23 23:59:45.245881+0800 KVOTest[17729:646223] 1
2021-02-23 23:59:45.253879+0800 KVOTest[17729:646135] *** Terminating app due to uncaught exception NSDestinationInvalidException, reason: *** -[ViewController performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform
*** First throw call stack:

从报错来看,在执行testhaha方法的时候,线程已经退出

解决方法,开启runloop,延长线程的时间:

NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"1");
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
    }];
    [thread start];
    [self performSelector:@selector(testhaha) onThread:thread withObject:nil waitUntilDone:true];

- (void)testhaha {
    NSLog(@"2");
}

 

OC原理之多线程(二)

标签:fir   invalid   kvo   val   first   mod   uncaught   The   代码   

原文地址:https://www.cnblogs.com/muzichenyu/p/14438984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!