NSOperation:
//NSOperation和NSThread最主要的区别是:前者是通过创建线程池,把任务添加到线程池来实现多线程并发操作。通过NSOperationQueue可以设置任务的调度顺序和最大并发数,以此达到任务的相对独立运行,而NSThread是通过加锁的方式来保证线程间的独立运行,来保证数据的准确性。
1:NSOperation基本概念
2:NSOperation的创建
3:NSOperation的使用
NSOperation常用方法:
NSOperationQueue:任务队列
NSInocationOperation:任务对象类型
initWithTarget:创建任务
addOperation:operation:添加任务到队列中
setMaxConcurrentOperationCount:设置同时并发的任务数量
#import "ViewController.h"
@interface ViewController (){
//定义一个任务队列对象
NSOperationQueue *_oq;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *arr = @[@"添加新任务1到队列中",@"添加新任务2到队列中"];
// Do any additional setup after loading the view, typically from a nib.
for (int i=0; i<2; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100+i*80, 160, 40);
[btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:arr[i] forState:0];
btn.tag = 100+i;
}
//创建一个任务队列对象
_oq = [[NSOperationQueue alloc]init];
//设置最大并发任务的数量
[_oq setMaxConcurrentOperationCount:5];
}
- (void)pressBtn:(UIButton*)btn{
if(btn.tag == 100){
//创建一个执行任务
//P1:任务函数的拥有者
//P2:任务函数执行者
//P3:参数
NSInvocationOperation *iop = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(optAct1:) object:@"opt01"];
[_oq addOperation:iop];
NSInvocation *ivo = [[NSInvocation alloc]init];
ivo.target = self;
ivo.selector = @selector(optAct1:);
NSInvocationOperation *iop2 = [[NSInvocationOperation alloc]initWithInvocation:ivo];
[_oq addOperation:iop2];
}else if(btn.tag == 101){
//使用block语法快来进行任务处理
[_oq addOperationWithBlock:^{
while (true) {
NSLog(@"opt 2");
}
}];
}
}
- (void)optAct1:(NSInvocationOperation*)opt{
while (true) {
NSLog(@"opt 1");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}