多线程-图片顺序出现

#import "ViewController.h"

#define Url @"http://www.bz55.com/uploads/allimg/150309/139-150309101A0.jpg"
#define Url1 @"http://www.bz55.com/uploads/allimg/150309/139-150309101F2.jpg"
#define Url2 @"http://www.bz55.com/uploads/allimg/150309/139-150309101A8.jpg"
#define Url3 @"http://pic38.nipic.com/20140215/12359647_224249442128_2.jpg"
#define Url4 @"http://pic38.nipic.com/20140215/12359647_224250481137_2.jpg"
#define Url5 @"http://img2.3lian.com/2014/f5/158/d/86.jpg"


@interface ViewController (){
    
    
//    定义一个全局变量的tag 用来判断UIImageView
    int index;
    NSMutableArray *threadArray;
    NSArray *array;
    UIImage *image;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
   
    threadArray = [NSMutableArray array];
    index = 100;
//    创建多个UIImageView
    for (int i = 0; i<3; i++) {
        for (int j = 0; j<2; j++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+j*210, 10+i*210, 200, 200)];
            imageView.backgroundColor = [UIColor redColor];
            imageView.tag = index++;
            [self.view addSubview:imageView];
            
        }
    }
//    创建线程
    for (int i = 0; i<6; i++) {
//        创建手动开启的线程
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread:) object:@(i)];
        
//        开启线程
        [thread start];
        
//        把线程添加到线程数组里
        [threadArray addObject:thread];
        
    }

}

- (void)thread:(NSNumber *)sender{
    
//    通过线程休眠来实现 顺序加载
    [NSThread sleepForTimeInterval:[sender intValue]];
    array = @[Url,Url1,Url2,Url3,Url4,Url5];
   //    给image添加数据
    image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:array[[sender intValue]]]]];
   
//    判断当前的线程是否被取消
    if ([NSThread currentThread].isCancelled) {
//        如果被取消 就退出线程
        [NSThread exit];
    }
//    回到主线程
    [self performSelectorOnMainThread:@selector(updateUI:) withObject:sender waitUntilDone:YES];
   
}

-(void)updateUI:(NSNumber *)sender{
    
    UIImageView *imageView = [self.view viewWithTag:[sender intValue]+100];
    
    imageView.image = image;
    
}
//点击view 触发
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    for (int i = 0; i<6; i++) {
//       取出线程数组里面的 线程对象
        NSThread *thread = threadArray[i];
        if (thread.isFinished == NO) {
            [thread cancel];
        }
 
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值