我们把一些耗时操作放在子线程,例如下载图片,但是下载完毕我们不能在子线程更新UI,因为只有主线程才可以更新UI和处理用户的触摸事件,否则程序会崩溃。此时,我们就需要把子线程下载完毕的数据传递到主线程,让主线程更新UI,这就是线程间的通信。
原理
代码
// 点击屏幕开始下载图片
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"当前线程1=%@",[NSThread currentThread]);
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"当前线程2=%@",[NSThread currentThread]);
NSString *strURL = @"http://pic33.nipic.com/20130916/3420027_192919547000_2.jpg";
UIImage *image = [self downloadImageWithURL:strURL];
if (image) {
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
}
}];
[thread start];
}
日志
2016-11-04 13:47:04.532 TTTTTTTTTT[10584:122182] 当前线程1=<NSThread: 0x600000260c80>{number = 1, name = main}
2016-11-04 13:47:04.533 TTTTTTTTTT[10584:122269] 当前线程2=<NSThread: 0x600000265d80>{number = 3, name = (null)}
子线程与主线程的回调应用的非常普遍。因为我们下载的数据大多数情况都是为了更新UI或者处理用户的触摸事件。其实在开发中,我们用NSThread的次数并不多,因为线程的同步、加锁都会造成一定的性能开销,我们还要手动管理线程的生命周期,很麻烦。开发的时候我们最多用的就是[NSThread currentThread]这个方法来判断一下当前线程。
这一篇应该是关于NSThread最后一篇文章了,从下一篇开始讲GCD。