#线程间通讯
- 从网络中下载一张图片放入到UIImageView中
- (void)touchBegin:(NSSet *)touches withEvent:(UIEvent *)event{ //1.下载图片 /* //测试执行时间 //NSDate *begin = [NSDate date]; CFAbsoluteTime begin = CFAbsoluterTimeGetCurrent(); //从网络下载一张图片 NSURL *url = [NSURL URLWihtString:@"图片资源网址"]; NSData *data = [NSData dataWithContentsOfURL:url];//耗时,应开启子线程 //NSDate *end = [NSDate date]; //NSLog(@"%f",[end timeIntervalSincedate:begin]); CFAbsoluteTime end = CFAbsoluteTimeGetCurrent(); NSLog(@"%f",end - begin); //2.将二进制转换为图片 UIImage *image = [UIImage imageWithData:data]; //3.显示图片 self.imageView.image = image; */ //开启一个子线程,下载图片 [self performSelectorInBackground:@selector(download) withObject:nil];}
- (void)download{ //1.下载图片 NSURL *url = [NSURL URLWihtString:@"图片资源网址"]; NSData *data = [NSData dataWithContentsOfURL:url];//耗时,应开启子线程 //2.将二进制转换为图片 UIImage *image = [UIImage imageWithData:data]; //3.更新UI#warning 注意:千万不要再子线程中更新UI,会出问题 //self.imageView.image = image;//不能子子线程中更新UI //在主线程中更新UI [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];//开发中常用 //[self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES]; NSLog(@"------");}- (void)updateImage:(UIImage *)image{ NSLog(@"++++++++"); self.imageView.image = image;}
- waitUntilDone:
- 如果传入YES,那么会等待@selector中的函数执行完毕,就可以执行之后的代码
- 如果传入NO,那么不会等待@selector中的函数执行完毕,就可以执行之后的代码
更新UI的方法
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
[self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES]; - (void)updateImage:(UIImage *)image{ self.imageView.image = image;}
- 3.使用:performSelector:(了解)
[self performSelector:@selector(updateImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; - (void)updateImage:(UIImage *)image{ self.imageView.image = image;}