//网络
// ViewController.m多线程
// NSThreadide
//spa
// Created by dc008 on 15/12/24..net
// Copyright © 2015年 崔晓宇. All rights reserved.线程
//3d
#import "ViewController.h"orm
@interface ViewController ()对象
{ //用于显示下载的图片图片
UIImageView *_imageView;
}
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self layout];
}
- (void)layout{
_imageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
_imageView.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:_imageView];
//下载按钮
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(120, 420, 80, 20)];
[button setTitle:@"加载图片" forState:UIControlStateNormal];
[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
[self.view addSubview:button];
}
- (void)noNSThread{
//在资源下载加载的过程当中,因为网络缘由,有时候咱们是很难保证下载时间的,若是不使用多线程可能用户完成一个下载操做须要很长时间的等待,并且在这个过程当中没法进行其余操做-》阻塞。
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img2.3lian.com/2014/f7/5/d/22.jpg"]]];
_imageView.image = image;
}
#pragma mark 多线程下载图片
- (void)loadImageWithMultiThread{
//方法1:使用对象方法
//建立一个线程
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
[thread1 start];//启动一个线程,并不表明当即执行,而是处于就绪状态,当系统调度时才真正执行
//方法2.使用类方法
// [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
}
- (void)loadImage{
//请求图片数据
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img2.3lian.com/2014/f7/5/d/22.jpg"]];
//注意只能在主线程中更新UI
//performSelectorOnMainThread 这个方法是NSObject的分类方法,每一个NSObject对象都有这个方法
[self performSelectorOnMainThread:@selector(updataImageView:) withObject:data waitUntilDone:YES];
}
- (void)updataImageView : (NSData *)imageData{
UIImage *image = [UIImage imageWithData:imageData];
_imageView.image = image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end