多線程併發下載圖片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
相關文章
相關標籤/搜索