您的位置:首页 > 产品设计 > UI/UE

NSOperationQueue(多线程请求队列)

2017-06-22 17:10 369 查看

我的控件都是拖控件的



#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageViewTp1;
@property (weak, nonatomic) IBOutlet UIImageView *imageViewTp2;
@property (weak, nonatomic) IBOutlet UIImageView *imageViewTp3;
@property (weak, nonatomic) IBOutlet UIImageView *imageViewTp4;

@property (retain)NSMutableArray* urlArr;
//创建请求队列
@property (retain)NSOperationQueue* queue;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//开辟空间
_urlArr = [NSMutableArray new];

NSString* urlString1 = @"http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg";
NSString* urlString2 = @"http://pic55.nipic.com/file/20141208/19462408_171130083000_2.jpg";
NSString* urlString3 = @"http://pic11.nipic.com/20101214/213291_155243023914_2.jpg";
NSString* urlString4 = @"http://pic.58pic.com/58pic/14/27/45/71r58PICmDM_1024.jpg";

[_urlArr addObject:urlString1];
[_urlArr addObject:urlString2];
[_urlArr addObject:urlString3];
[_urlArr addObject:urlString4];
}

- (IBAction)loadingAction:(UIButton *)sender {
//创建请求队列,队列放的是一个个异步请求线程
_queue = [[NSOperationQueue alloc]init];
for (NSInteger i = 0; i < 4; i++) {
//创建请求线程
NSArray* arr = @[_urlArr[i],[NSString stringWithFormat:@"%ld", i+10]];
NSInvocationOperation* opertation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:arr];
//把线程加载到队列中,让队列去实现开始和结束
[_queue addOperation:opertation];
}
}
- (IBAction)suspendedAction:(UIButton *)sender {
//取消所有线程的执行
[_queue cancelAllOperations];
}

-(void)downloadImage:(NSArray*)arr
{
NSURL* url = [NSURL URLWithString:arr[0]];
NSData* data = [NSData dataWithContentsOfURL:url];
UIImage* image = [UIImage imageWithData:data];
UIImageView* imageView  = [self.view viewWithTag:[arr[1] integerValue]];
imageView.image = image;
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程