NSOperation浅析
来源:互联网 发布:打印文件软件 编辑:程序博客网 时间:2024/06/06 15:36
NSOperation是苹果提供给我们的一套多线程解决方案,它是基于GCD开发的,但是比GCD拥有更强的可控性和代码可读性。
NSOperation是一个抽象基类,我们使用最多的是系统封装好的NSInvocationOperation和NSBlockOperation。
一、NSOperation通用方法
NSOperation * operation = [[NSOperation alloc]init];
//开始执行
[operation start];
//取消执行
[operation cancel];
//执行结束后调用的Block
[operation setCompletionBlock:^{
NSLog(@"执行结束");
}];
二、NSInvocationOperation
NSInvocationOperation是同步执行的,需要配合NSOperationQueue去使用
//创建
NSInvocationOperation * invo = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(testNSInvocationOperation) object:nil];
//执行
[invo start];
- (void)testNSInvocationOperation
{
NSLog(@"我在第%@个线程",[NSThread currentThread]);
}
三、NSBlockOperation
NSBlockOperation是NSOperation的子类,支持并发的实行一个或多个block。
NSBlockOperation会优先将block放到主线程中执行,若主线程已有待执行的代码,就开辟新的线程,但最大并发数为4(包括主线程在内)。如果block数量大于了4,那么剩下的Block就会等待某个线程空闲下来之后被分配到该线程,且依然是优先分配到主线程。
四、NSOperation
不大需要
五、NSOPerationQueue
NSOperationQueue就是执行NSOperation的队列,我们可以将一个或多个NSOperation对象放到队列中去执行
//依然调用上面的那个方法
NSInvocationOperation * invo = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(testNSInvocationOperation) object:nil];
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
[queue addOperation:invo];
NSOperationQueue提供了一个更加简单的方法
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{
//这里是你想做的操作
}];
添加依赖关系
假如A依赖于B,那么在B执行结束之前,A将永远不会执行
NSInvocationOperation * op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(testNSInvocationOperation1) object:nil];
NSInvocationOperation * op2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(testNSInvocationOperation2) object:nil];
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
[op2 addDependency:op1];
[queue addOperation:op1];
[queue addOperation:op2];
- (void)testNSInvocationOperation1
{
NSLog(@"我是op1 我在第%@个线程",[NSThread currentThread]);
}
- (void)testNSInvocationOperation2
{
NSLog(@"我是op2我在第%@个线程",[NSThread currentThread]);
}
- NSOperation浅析
- NSOperation、NSOperationQueue浅析
- NSOperation
- NsOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- NSOperation
- Android在自己的应用中启动第三方应用
- 数据库表空间不足
- C/C++ — 实现日期计算器
- Android应用如何适配不同的屏幕
- hashCode()函数详解
- NSOperation浅析
- MYSQL
- 模态框回车搜索的实现
- Linux C多线程
- 判断二进制数除以3的余数
- ffmpeg录制屏幕,生成MP4视频文件开发过程
- iOS中的runtime源码简要分析(一)
- EditText显示隐藏密码
- hdu 1025 Constructing Roads In JGShining's Kingdom LIS最长上升序列