- 1个线程传递数据给另1个线程
- 在1个线程中执行完特定任务后,转到另1个线程继续执行任务
// 子线程返回主线程可以用这个方法
- (void)performSelectorOnMainThread:(SEL)aSelector
withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr
withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);
[实例]
// 触摸后开始下载图片,并显示
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 下载图片到本地,下载费时间后台开启线程进行下载
[self performSelectorInBackground:@selector(downLoadImage) withObject:nil];
}
/**
* 子线程,完成下载图片的任务。
*/
- (void)downLoadImage {
// iOS9中的http请求全部改用https,若要http必须修改info.plist文件
// NSAppTransportSecurity -- 添加字典
// NSAllowsArbitraryLoads -- 添加item 设置值为 YES
NSURL *url = [NSURL URLWithString:@"http://a3.qpic.cn/psb?/76485577-
db8b-4a97-9c1e-e9d919af5bc5/5bQwZ7UhPw9GFhw3RNb*C8FlavddPlGHIrXehxNIHvw!
/b/dB4BAAAAAAAA&ek=1&kp=1&pt=0&bo=gAJxBAAAAAAFANQ!&sce=0-12-12&rf=viewer
_311"];
NSData *data = [NSData dataWithContentsOfURL:url];
// 更新、显示UI界面一定要在主线程否则不安全
UIImage *image = [UIImage imageWithData:data];
// 回到主线程显示图片
[self performSelectorOnMainThread:@selector(displayImage:)
withObject:image waitUntilDone:NO];
}
/**
* 主线程,设置图片
*/
- (void)displayImage: (UIImage *)image {
[self.imageView setImage:image ];
}
设置图片可以用下面的代码一行搞定
// 回到主线程显示图片
[self.imageView performSelectorOnMainThread:@selector(setImage:)
withObject:image waitUntilDone:NO];