NSOperation 任务
NSInvocationOperation、NSBlockOperation是它的子类我们平时只对这两个子类进行操作
NSInvocationOperation初始化方法:
NSInvocationOperation* op = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(runOP)object:nil];
[opstart];
NSBlockOperation初始化方法:
NSBlockOperation* op1 = [NSBlockOperationblockOperationWithBlock:^{
NSLog(@"op1 == %@",[NSThreadcurrentThread]);//主线程执行
}];
[op1addExecutionBlock:^{
NSLog(@"op12 == %@",[NSThreadcurrentThread]);//非主线程执行
}];
[op1start];
NSOperationQueue 队列
NSOperationQueue* queue = [[NSOperationQueuealloc]init];//创建队列 会开启新的线程
//NSOperationQueue * queue = [NSOperationQueue mainQueue];//创建主线程队列 执行这个队列里的任务不会开启新的线程(addExecutionBlock:^{}]除外)
queue.maxConcurrentOperationCount=1;//串行
queue.maxConcurrentOperationCount=-1;//并行
queue.maxConcurrentOperationCount=2 3 4...;//指定并发数
[opaddDependency:op1];//依赖关系op1执行完成后才会执行op
[queue addOperation:op];任务到加入队列中
[queue addOperation:op1];
[queue addOperationWithBlock:^{
NSLog(@"que == %@",[NSThreadcurrentThread]);
}];
注意加入队列中的任务不需要start 否则会crash.
网友评论