NSOperation官方文档及使用(一)

来源:互联网 发布:sql数据备份 编辑:程序博客网 时间:2024/06/05 03:30

一、几个概念

thread线程:用于指代码的单独执行路径。 OS X中线程的底层实现基于POSIX线程API。
process进程:用于指运行的可执行文件,其可以包含多个线程。
task任务:用于指代需要执行的工作的抽象概念。
操作:Cocoa中操作是一种面向对象的方式,用于封装我们要异步执行的工作。 操作被设计为与操作队列结合使用或者由它们自己使用。

二、介绍操作如何定义和使用的

1、关于Operation对象
Operation对象是NSOperation类的实例,Operation对象用来封装你想要做的工作;NSOperation类是一个抽象类,如果我们要使用他的话,必须使用他的子类NSInvocationOperation、NSBlockOperation或者你自定义一个Operation类。
所有的操作对象均支持一下特征
(1)支持在操作对象之间的依赖关系。这些依赖关系阻止给定的操作的运行,直到它所依赖的操作执行完毕后才开始执行给定的操作
(2)支持可选的完成块,在操作的主任务完成后才开始执行可选的完成块
(3)支持使用KVO监视操作执行状态的改变
(4)支持优先级操作,从而影响执行的相对顺序
(5)支持取消语义,允许在执行时暂停操作

2、创建Operation对象
(1)NSInvocationOperation:是一个基于对象和selector的Operation,使用这个你只需要指定对象以及任务的selector,如果必要,你还可以设定传递的对象参数。 特别是如果您正在修改现有应用程序,并且程序中已经具有执行必要任务所需的对象和方法时,使用此类可以避免在应用程序中为每个任务定义大量的自定义操作对象; 当您要调用依情况而改变的方法可时,也可以使用它。

@implementation MyCustomClass- (NSOperation*)taskWithData:(id)data {    NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data];   return theOp;}// This is the method that does the actual work of the task.- (void)myTaskMethod:(id)data {    // Perform the task.}@end

同时当这个Operation完成后,你还可以获取Operation中Invation执行后返回的结果对象。

id result = [invacationOperation result]; 

(2)NSBlockOperation:当需要同时执行一个或多个块对象时,可以使用NSBlockOperation来创键operation对象,因为他可以执行多个块,且只有当所有的相关块都执行完时才认为操作本身执行完。此类为已经使用操作队列,但是不想创建dispatch queue的程序提供面向对象的包装器。
创建块操作时,通常在初始化时添加至少一个块; 但可以稍后根据需要添加更多块。 当执行NSBlockOperation对象时,对象将所有块提交到默认优先级的并发分派队列中。 当最后一个块完成执行时,操作对象将自己标记为已完成。 因此,您可以使用块操作来跟踪一组执行块,就像使用线程连接来合并多个线程的结果一样。 区别是因为块操作本身运行在一个单独的线程上,您的应用程序的其他线程可以在等待块操作完成时继续工作

NSBlockOperation* theOp = [NSBlockOperation blockOperationWithBlock: ^{      NSLog(@"Beginning operation.\n");      // Do some work.   }];

注意:(1)在使用- (void)addExecutionBlock:(void (^)(void))block;
追加操作时,必须在调用start方法之前,否则会报错blocks cannot be added after the operation has started executing or finished’
(2)使用addExecutionBlock:追加的块,与初始化使用的块是并发执行的
具体例子可以使用Demo验证,这里就不贴代码了。

创建块操作对象后,可以使用addExecutionBlock:方法向其中添加更多块。 如果需要连续执行块,则必须将它们直接提交到所需的分派队列。

(3)NSOperation:是一个基类,可以用来自定义operation对象,子类化NSOperation,你可以完全控制操作的实现,包括更改操作执行的默认方式或报告操作执行的状态。
NSOperation类为所有操作对象提供了一个通用子类化模型。 该类还提供了大量的基础设施来处理依赖项和KVO通知所需的大部分工作。 但是,有时候您可能需要补充现有的基础架构,以确保您的操作正常运行。 您必须执行的额外工作量取决于您是实施非并发还是并发操作。

三、NSInvocationOperation以及NSBlockOperation详细使用
(1)NSInvocationOperation

- (void)viewDidLoad {    [super viewDidLoad];    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"NSOperation" forKey:@"练习NSOperation"]; //传递给invoOper方法一个对象,执行的操作方法与调用start的方法在同一个线程,并且是同步执行的方法执行完毕,satrt才执行完    NSInvocationOperation *invoOper = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationSelector:) object:dic];    NSLog(@"start before:%@",[NSThread currentThread]);    [invoOper start];    NSLog(@"start sfter:%@",[NSThread currentThread]);}-(void)operationSelector:(NSDictionary *)dict{    NSLog(@"dictValue=%@",[dict valueForKey:@"练习NSOperation"]);    sleep(10);    NSLog(@"current thread=%@",[NSThread currentThread]);}

输出如下

start before:<NSThread: 0x7fb411405aa0>{number = 1, name = main}dictValue=NSOperationcurrent thread=<NSThread: 0x7fb411405aa0>{number = 1, name = main}Nsstart sfter:<NSThread: 0x7fb411405aa0>{number = 1, name = main}

(2)NSBlockOperation

//NSBlockOperation 与 NSInvocationOperation 的结果是一样的,Block 中的操作与start方法在同一个线程执行,并且是同步执行的NSBlockOperation *blOp = [NSBlockOperation blockOperationWithBlock:^{        sleep(5);        NSLog(@"current thread = %@",[NSThread currentThread]);        NSLog(@"main  thread = %@",[NSThread mainThread]);    }];    NSLog(@"start before: %@",[NSThread currentThread]);    [blOp start];    NSLog(@"start after: %@",[NSThread mainThread]);

输出

start before: <NSThread: 0x7fc652403290>{number = 1, name = main} current thread = <NSThread: 0x7fc652403290>{number = 1, name = main}main  thread = <NSThread: 0x7fc652403290>{number = 1, name = main}start after: <NSThread: 0x7fc652403290>{number = 1, name = main}

使用addExcexutionBlock来添加操作

    NSBlockOperation *blOp = [NSBlockOperation blockOperationWithBlock:^{        NSLog(@"1 start");        sleep(5);        NSLog(@"1 current thread = %@",[NSThread currentThread]);        NSLog(@"1 main  thread = %@",[NSThread mainThread]);        NSLog(@"1 end");    }];    [blOp addExecutionBlock:^{        NSLog(@"2 start");        sleep(5);        NSLog(@"2 current thread = %@",[NSThread currentThread]);        NSLog(@"2 main  thread = %@",[NSThread mainThread]);        NSLog(@"2 end");    }];    [blOp addExecutionBlock:^{        NSLog(@"3 start");        sleep(5);        NSLog(@"3 current thread = %@",[NSThread currentThread]);        NSLog(@"3 main  thread = %@",[NSThread mainThread]);        NSLog(@"3 end");    }];    NSLog(@"start before: %@",[NSThread currentThread]);    [blOp start];    NSLog(@"start after: %@",[NSThread mainThread]);
start before: <NSThread: 0x7fac51f04ec0>{number = 1, name = main}1 start2 start3 start1 current thread = <NSThread: 0x7fac51f04ec0>{number = 1, name = main} 1 main  thread = <NSThread: 0x7fac51f04ec0>{number = 1, name = main}1 end3 current thread = <NSThread: 0x7fac51d06e50>{number = 2, name = (null)}2 current thread = <NSThread: 0x7fac51d0a190>{number = 3, name = (null)}3 main  thread = <NSThread: 0x7fac51f04ec0>{number = 1, name = (null)}2 main  thread = <NSThread: 0x7fac51f04ec0>{number = 1, name = (null)}3 end 2 endstart after: <NSThread: 0x7fac51f04ec0>{number = 1, name = main}

看到Block1在主线程中完成, Block2 和 Block3 中的 currentThread 并不是主线程,而且其中的操作也是异步执行的,但是start方法在所有的操作都执行完毕后才表明执行完毕

注意:
如果在调用start方法后,在利用addExcutionBlock添加操作,将会crash
blocks cannot be added after the operation has started executing or finished’

四、总结

NSInvocationOperation和NSBlockOperation,如果仅是执行同步操作,没有什么区别,只不过是NSInvocationOperation使用selector回调,并且可以传参数进去,而NSBlockOperation使用block来封装要执行的任务代码。如果但是如果想要使用多线程异步操作,则应该选择 NSBlockOperation,不过注意只有通过addExecutionBlock添加的操作才是多线程异步操作。

demo:https://github.com/onebutterflyW/NSOperation

0 0
原创粉丝点击