申明:此为本人学习笔记,若有纰漏错误之处的可留言共同探讨
/*
多线程编程思路
1. 开启分线程,在分线程加载数据
2 加载完之后,回到主线程再更新UI
这里要强调一点,就是不要直接在分线程更新UI。不仅是IOS开发,其他的语言也是强调不要在主线程以外的线程更新UI。
*/
#import "ViewController.h"
@interface ViewController ()
{
UIImageView *view;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 用来显示网络加载过来的图片
view= [[UIImageView alloc]initWithFrame:self.view.frame];
[self.view addSubview:view];
// 开启分线程
[NSThread detachNewThreadSelector:@selector(loadPic) toTarget:self withObject:nil];
}
#pragma mark - 线程方法
- (void)loadPic
{
NSLog(@"loadThreadMethod");
// 加载网络图片
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://imgsrc.baidu.com/forum/pic/item/e42b1dd8bc3eb135d193e747a61ea8d3fc1f4493.jpg"]];
// 回到主线程
[self performSelectorOnMainThread:@selector(gotoMain:) withObject:data waitUntilDone:YES];
}
-(void)gotoMain:(NSData *)data
{
// 刷新UI数据
view.image = [UIImage imageWithData:data];
}
@end