@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];
}
}