方法一:
GCD
//在主线程里调用,然后跳到一个子线程。
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//IMAGE_URL为定位的宏。为图片的地址
//在子线程里完成对网上图片的解析
NSURL *imageURL = [NSURL URLWithString:IMAGE_URL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
//完成解析后然后跳到主线程里执行UIImageView的操作。
dispatch_async(dispatch_get_main_queue(), ^{
//创建一个UIImageView
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
//对UIImageView加载下载好的图片。
imageView.image = [UIImage imageWithData:imageData];
[self.window addSubview:imageView];
[imageView release];
});
});
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sonThreah) object:nil];
启动子线程
[thread start];
//实现子线程里的方法
-(void)sonThreah{
//跳到子线程,对图片进行解析
NSURL *imageURL = [NSURL URLWithString:IMAGE_URL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
//解析完跳到主线程
[self performSelectorOnMainThread:@selector(showImage:) withObject:imageData waitUntilDone:NO];
}
-(void)showImage:(NSData *)data {
//主线程完成对图片的加载
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.window addSubview:imageView];
imageView.image = [UIImage imageWithData:data];
[imageView release];
}