多线程并发下载图片NSThread

#import "ViewController.h"

#pragma mark 一下是一些宏定义的数据
#define ROW 5
#define COLUMN 3
#define IMAGE_COUNT ROW*COLUMN
#define WIDTH 100
#define HRIGHT WIDTH

@interface ViewController ()
{
    UIImageView *_image;
    NSMutableArray *_imageArray;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layout];
}

- (void) layout{
    _imageArray=[[NSMutableArray alloc]initWithCapacity:10];
    for (int i=0; i<ROW; i++) {
        for (int j=0; j<COLUMN; j++) {
            _image=[[UIImageView alloc]initWithFrame:CGRectMake(20+j*120, 20+i*120, 100, 100)];
            //默认的一张图片,下载后直接替换
            _image.image=[UIImage imageNamed:@"1"];
            [self.view addSubview:_image];
            [_imageArray addObject:_image];
        }
    }
    //添加按钮
    UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
    button.frame=CGRectMake(50, 620, 275, 30);
    [button setTitle:@"下载图片" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

#pragma mark 改变线程的优先级
//提高它被优先加载的几率,但是它也未必就第一个加载。1.其他进程是先启动的  2.网络状态无法保证
- (void) download{
    NSMutableArray *threads=[NSMutableArray array];
    for (int i=0; i<IMAGE_COUNT; i++) {
        NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
        thread.name=[NSString stringWithFormat:@"%i",i];
        //设置进程的优先级(0-1)
        if(i==IMAGE_COUNT-1){
            thread.threadPriority=1.0;
        }else{
            thread.threadPriority=0;
        }
        [threads addObject:thread];
    }
    
    for (int i=0; i<IMAGE_COUNT; i++) {
        NSThread *thread=threads[i];
        [thread start];
    }
}

- (void) loadImage : (NSNumber *) index{
    [NSThread sleepForTimeInterval:3];//线程休眠3S
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img8.9158.com/200909/22/21/57/200909224897541.jpg"]];
    NSArray *array=@[data,index];
    //只能在主线程里面才能够跟新UI--->withObject是否线程结束时执行
    //performSelectorOnMainThread 是NSObject的分类方法,每个NSObject对象都有这个方法
    [self performSelectorOnMainThread:@selector(updatImage:) withObject:array waitUntilDone:YES];
}

- (void) updatImage:(NSArray *)array{
    UIImage *image=[UIImage imageWithData:array[0]];
    UIImageView *iv=_imageArray[[array[1] intValue]];
    iv.image=image;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


你可能感兴趣的:(多线程并发下载图片NSThread)