实现功能: 从网络下载图片,显示在界面上
注意点:
1.Xcode 7开始默认使用HTTPS协议,可能需要修改plist文件
2.所有耗时操作都在子线程进行,防止卡死UI
3.几乎所有UIKit提供的类都是线程不安全的,所有更新UI的操作都在主线程上执行
示例代码:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.imageView];
// 异步下载图片
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
}
- (void)downloadImage{
// 根据URL下载图片
NSURL *url = [NSURL URLWithString:@"http://b.hiphotos.bdimg.com/wisegame/pic/item/d37eca8065380cd7107d123aa044ad3458828182.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主线程刷新UI
[self performSelectorOnMainThread:@selector(updateUIWithImage:) withObject:image waitUntilDone:NO];
}
- (void)updateUIWithImage:(UIImage *)image{
self.imageView.image = image;
}
@end

demo.png
这里回到主线程使用了:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
waitUntilDone: 代表是否等待当前代码执行完毕再执行后面的代码
如果设置YES,代表执行完后在执行performSelectorOnMainThread后面的代码
如果设置NO,代表不用等待performSelectorOnMainThread执行完就可以执行后面的代码
例如下面的代码,我讲waitUntilDone设置为YES,在回到主线程刷新UI时延迟5s执行,最终的效果就是,等刷新UI操作完成后,才会执行后面的打印
- (void)downloadImage{
// 根据URL下载图片
NSURL *url = [NSURL URLWithString:@"http://b.hiphotos.bdimg.com/wisegame/pic/item/d37eca8065380cd7107d123aa044ad3458828182.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主线程刷新UI waitUntilDone: 代表等待当前代码执行完毕再执行后面的代码
[self performSelectorOnMainThread:@selector(updateUIWithImage:) withObject:image waitUntilDone:YES];
NSLog(@"回到主线程刷新UI操作完毕");
}
- (void)updateUIWithImage:(UIImage *)image{
[NSThread sleepForTimeInterval:5];
self.imageView.image = image;
}
同理,如果设置为NO,在刷新UI前就可以执行打印这一句代码了