1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| //网络图片下载Demo -- NSThread实现 #import "ViewController.h"
@interface ViewController ()
@property(nonatomic, strong) UIImageView *imageView; @property(nonatomic, strong) NSThread *threadA;
@end
@implementation ViewController
//耗时操作要用子线程进行 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //分离一条子线程去执行download方法 [NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil]; }
- (void)download { //确定图片URL NSURL *url = [NSURL URLWithString:@"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa1.att.hudong.com%2F62%2F02%2F01300542526392139955025309984.jpg&refer=http%3A%2F%2Fa1.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613890070&t=9b041b83f4ddfe8c165547120f5aa589"]; //根据URL下载图片二进制数据到本地 NSData *imageData = [NSData dataWithContentsOfURL:url]; //图片格式转换 UIImage *image = [UIImage imageWithData:imageData]; //回到主线程显示UI的三种方法 //方法1 /* 参数1:回到主线程要调用的方法 参数2:前面方法需要的参数 参数3:当前方法剩余部分的执行是否等待参数1方法执行完毕 */ [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES]; //方法2 -- 主动选择执行线程为主线程 [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; //方法3 -- 直接用self.imageView调用主线程方法 [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES]; }
- (void)showImage:(UIImage *)image { self.imageView.image = image; } @end
|