多线程-图片顺序出现

来源:互联网 发布:景安已备案域名 编辑:程序博客网 时间:2024/04/30 07:38
#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];
        }
 
    }
}

1 0
原创粉丝点击