GCD线程通讯
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
NSLog(@"dispatch_async globalQueue begin !!! %@", [NSThread currentThread]);
// 耗时操作
NSString *str = @"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回主线程,更新图片;
dispatch_queue_t mainQueue = dispatch_get_main_queue();
// 阻塞当前线程,等待block执行完毕后,向下执行
//dispatch_sync(mainQueue, ^{
// 不阻塞当前线程,直接执行下面的操作,无需等待block
dispatch_async(mainQueue, ^{
NSLog(@"image.size.width...%f", image.size.width);
NSLog(@"mainQueue !!! %@", [NSThread currentThread]);
self.imageView.image = image;
});
NSLog(@"dispatch_async globalQueue end !!! %@", [NSThread currentThread]);
});
NSThread线程通讯
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"Hello World ! 111111 %@", [NSThread currentThread]);
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
NSLog(@"Hello World ! 222222 %@", [NSThread currentThread]);
}
- (void)downloadImage {
NSLog(@"downloadImage begin !!! %@", [NSThread currentThread]);
NSString *str = @"http://sinastorage.com/storage.zone.photo.sina.com.cn/zone/img/20161101/eb1721bdb2e5b6d85534833d249a3bff.jpg?&ssig=tW2%2BnBxmjp&KID=sina,slidenews&Expires=1478091012";
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 线程通信
// 子线程回主线程
// 1.定义一个loadImage方法,为imageView赋值
//[self performSelectorOnMainThread:@selector(loadImage:) withObject:image waitUntilDone:NO];
//[self performSelector:@selector(loadImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
// 2.使用imageView自带的setImage方法赋值
[imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
NSLog(@"downloadImage end !!! %@", [NSThread currentThread]);
}
- (void)loadImage:(id)obj {
imageView.image = obj;
NSLog(@"loadImage end !!! %@", [NSThread currentThread]);
}
网友评论