標籤:
上一節《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 子類實現及並發執行