标签:
上一节《iOS NSOperation 非并发执行》中已经讲了NSOperation中系统提供的子类NSBlockOperation和NSInvocationOperation的任务的非并发执行,以及添加到NSOperationQueue中进行并发执行。这节将NSOperation 子类实现以及并发执行。
NSOperation非并发子类实现,只需重盖main方法,将要执行的任务放到main方法中,在main方法中要做cancel判断的,如下例:
@interface MyNonConcurrentOperation : NSOperation
@property (strong) id myData;
- (id)initWithData:(id)data;
@end
@implementation MyNonConcurrentOperation
- (id)initWithData:(id)data
{
if (self = [super init])
{
_myData = data;
}
return self;
}
- (void)main
{
@try {
BOOL isDone = NO;
while (![self isCancelled] && !isDone) {
// Do some work and set isDone to YES when finished
}
}
@catch(...) {
// Do not rethrow exceptions.
}
}
@end
NSOperation 并发子类实现,必须覆盖 start、isConcurrent、isExecuting和isFinished四个方法,main方法可选
@interface MyOperation : NSOperation {
BOOL executing;
BOOL finished;
}
- (void)completeOperation;
@end
@implementation MyOperation
- (id)init {
self = [super init];
if (self) {
executing = NO;
finished = NO;
}
return self;
}
- (BOOL)isConcurrent {
return YES;
}
- (BOOL)isExecuting {
return executing;
}
- (BOOL)isFinished {
return finished;
}
- (void)start {
// Always check for cancellation before launching the task.
if ([self isCancelled])
{
// Must move the operation to the finished state if it is canceled.
[self willChangeValueForKey:@"isFinished"];
finished = YES;
[self didChangeValueForKey:@"isFinished"];
return;
}
// If the operation is not canceled, begin executing the task.
[self willChangeValueForKey:@"isExecuting"];
[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
executing = YES;
[self didChangeValueForKey:@"isExecuting"];
}
- (void)main {
@try {
// Do the main work of the operation here.
[self completeOperation];
}
@catch(...) {
// Do not rethrow exceptions.
}
}
- (void)completeOperation {
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
executing = NO;
finished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
@end
NSOperation 的属性添加了KVO机制,当我们覆盖属性的getter方法,按我们指定的状态返回,所以在状态改变时要发起KVO通知,通知监听次属性的对象。在start方法中使用NSThread 开启了新线程实现并发执行。
iOS NSOperation 子类实现及并发执行
标签:
原文地址:http://www.cnblogs.com/shuleihen/p/4377418.html