@interface ViewController ()
/** 图片视图*/
@property(nonatomic,weak) UIImageView * imageView;
/** 图片数组*/
@property(nonatomic,strong) NSMutableArray * imageArray;
/** 存储线程*/
@property(nonatomic,strong) NSMutableArray * threadArray;
@end
//对象方法cancle,可以在外部使用。
//类方法exit,写在线程内部,结束当前现线程。
//两者结合使用,使用cancle进行标记,使用exit退出
@implementation ViewController
- (NSMutableArray *)imageArray
{
if (_imageArray==nil) {
_imageArray =[NSMutableArray array];
}
return _imageArray;
}
- (NSMutableArray *)threadArray
{
if (_threadArray==nil) {
_threadArray =[NSMutableArray array];
}
return _threadArray;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//加载视图
[self _loadViews];
//开启多线程加载图片
[self _openMultiThread];
}
//======加载这个,可以在主线程中加载
- (void) _loadViews
{
for (int i=0;i<15; i++)
{
int col=i%3;
int row=i/3;
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(22+col*(80+45), 40+row*(100+20), 90, 90)];
imageView.backgroundColor=[UIColor redColor];
[self.imageArray addObject:imageView];
[self.view addSubview:imageView];
}
// 添加按钮
UIButton * button=[UIButton buttonWithType:UIButtonTypeContactAdd];
button.frame=CGRectMake(0, 20, 20, 20);
[button addTarget:self action:@selector(btClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
//开启多线程加载图片
- (void) _openMultiThread
{
for (int i=0; i<self.imageArray.count; i++)
{
// [NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:@(i)];
// 要存数组就不能使用类方法创建线程
NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage:) object:@(i)];
[thread start];
[self.threadArray addObject:thread];
}
}
- (void)loadImage:(NSNumber *) number
{
//取到索引
NSInteger index=[number integerValue];
NSString * imageSrc=@"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%d.jpg";
imageSrc=[NSString stringWithFormat:imageSrc,index];
NSURL * URL=[NSURL URLWithString:imageSrc];
NSData * data=[NSData dataWithContentsOfURL:URL];
UIImage *image=[UIImage imageWithData:data];
//封装model
ImageModel * model=[[ImageModel alloc] init];
model.image=image;
model.index=index;
//如果状态为删除,则退出线程
NSThread * thread = [NSThread currentThread];
if ([thread isCancelled])
{
[NSThread exit];//执行exit,后边的语句不再执行。所以不用写return
//return也可以退出进程,一旦退出就不能再使用start开启
}
NSLog(@"%@", thread);
[self performSelectorOnMainThread:@selector(showImage:) withObject:model waitUntilDone:NO];
}
//回到主线程更新图片
- (void) showImage:(ImageModel *) model
{
UIImageView * imageView=self.imageArray[model.index];
imageView.image=model.image;
}
#pragma mark - 点击事件
- (void)btClick
{
// 当点击按钮时,对所有线程进行标记
for (NSThread * t in self.threadArray)
{
[t cancel];
}
}