NSOperation/NSOperationQueue面向对象的线程技术。
NSOperation:不需要关心线程管理,数据同步的事情,可以把精力放在自己需要执行的操作上。NSOpertion是面向对象的。
NSOperation的创建以及常用的方法:
1 //创建线程队列 2 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 3 4 //关闭暂停队列,用于让所有的线程加入队列后在执行任务 5 [queue setSuspended:YES]; 6 7 //设置最大并发数, 8 queue.maxConcurrentOperationCount = 2; 9 10 //创建线程 11 NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operation1:) object:@"operation1"]; 12 13 //设置线程优先级 14 operation1.queuePriority = NSOperationQueuePriorityNormal; 15 16 //创建第二个线程 17 NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operation2:) object:@"operation2"]; 18 //设置线程优先级 19 operation2.queuePriority = NSOperationQueuePriorityVeryHigh; 20 21 //将线程加入队列 22 [queue addOperation:operation1]; 23 [queue addOperation:operation2]; 24 25 26 //用Block创建多线程 27 28 [queue addOperationWithBlock:^{ 29 30 //注意这里我们要将任务放进自动释放池,因为这段代码不在(主线程)中 31 @autoreleasepool { 32 33 for (int i = 0; i < 10; i ++) { 34 35 NSLog(@"operation3%d",i); 36 } 37 } 38 }]; 39 40 41 //开始队列 42 [queue setSuspended:NO];
说完创建方式及常用方法,属性。也来说说其解决主线程阻塞的问题
例子跟上篇文章大致是一样的。
类目中的主要代码:
#import "UIImageView+cache.h" @implementation UIImageView (cache) - (void)setImages:(NSString *)str { //创建队列 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //设置最大并发 queue.maxConcurrentOperationCount = 1; //创建线程 NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationAction:) object:str]; //将线程加入线程队列 [queue addOperation:operation]; } - (void)operationAction:(NSString *)str { NSURL *url = [NSURL URLWithString:str]; NSData *data = [NSData dataWithContentsOfURL:url]; //在这里我们要修改UI了所以要重新回到主线程 //第一种回主线程的方式 [self performSelectorOnMainThread:@selector(setImage:) withObject:[UIImage imageWithData:data] waitUntilDone:YES]; /* //第二种方式回到主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.image = [UIImage imageWithData:data]; }]; */ } @end viewController中的代码: #import "ViewController.h" #import "UIImageView+cache.h" @interface ViewController () @property (nonatomic, strong)NSMutableArray *dataArr; @end @implementation ViewController - (NSMutableArray *)dataArr { if (_dataArr == nil) { _dataArr = [NSMutableArray array]; return _dataArr; } return _dataArr; } - (void)viewDidLoad { [super viewDidLoad]; for (int i = 0; i < 8; i ++) { for (int j = 0; j < 6; j ++) { UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(j * 64, i * 80, 60, 75)]; imageview.backgroundColor = [UIColor yellowColor]; [self.view addSubview:imageview]; [self.dataArr addObject:imageview]; } } } - (IBAction)click:(UIButton *)sender { for (UIImageView *imageview in self.dataArr) { [imageview setImages:@"http://img31.mtime.cn/pi/2013/03/08/144644.81111130_1280X720.jpg"]; } } @end 这样就解决了主线程阻塞的问题。
时间: 2024-11-06 16:52:51