自定义NSOperation
2021-05-19 本文已影响0人
哈哈哈我的简书账号
NSInvocationOperation和NSBlockOperation是系统默认的子类实现,属于同步operation。
实现类似于
@interface NSInvocationOperation ()
@property (getter=isExecuting) BOOL executing;
@property (getter=isFinished) BOOL finished;
@end
@implementation NSInvocationOperation
@synthesize finished = _finished;
@synthesize executing = _executing;
- (void)main {
@synchronized (self) {
if (self.isCancelled) {
self.finished = YES;
self.executing = NO;
return;
}
self.finished = NO;
self.executing = YES;
if (self.executionBlock) {
self.executionBlock();
}
self.finished = YES;
self.executing = NO;
}
}
- (void)cancel {
@synchronized (self) {
[super cancel];
if (self.isExecuting) {
self.executing = NO;
self.finished = YES;
}
}
}
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
- (BOOL)isAsynchronous {
return NO;
}
@end
如果operation进行网络请求或者异步的任务,就需要自定义异步任务
@class BBAAsyncOperation;
typedef void (^BBAAsyncOperationExecutionBlockType)();
@interface BBAAsyncOperation : NSOperation
@property (nonatomic, copy) BBAAsyncOperationExecutionBlockType executionBlock;
- (void)done;
@end
#import "BBAAsyncOperation.h"
@interface BBAAsyncOperation ()
@property (assign, getter = isExecuting) BOOL executing;
@property (assign, getter = isFinished) BOOL finished;
@end
@implementation BBAAsyncOperation
@synthesize executing = _executing;
@synthesize finished = _finished;
// 异步任务会出发start方法
- (void)start {
@synchronized (self) {
if (self.isCancelled) {
self.finished = YES;
return;
}
self.finished = NO;
self.executing = YES;
if (self.executionBlock) {
self.executionBlock();
} else {
self.executing = NO;
self.finished = YES;
}
}
}
// 自定义方法,异步任务完成,回调,结束任务
- (void)done {
@synchronized (self) {
if (self.isExecuting) {
self.finished = YES;
self.executing = NO;
}
}
}
- (void)cancel {
@synchronized (self) {
[super cancel];
if (self.isExecuting) {
self.executing = NO;
self.finished = YES;
}
}
}
// 父类中的属性声明为readonly,不能触发KVO,这里需要手动实现KVO
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
- (BOOL)isAsynchronous {
// 返回YES
return YES;
}
@end
1:对属性executing和finished的访问需要保证同步,这里使用@synchronized (self) {
}实现
2:自定义需要实现start,isAsynchronous,setFinished:,setExecuting:方法。
官方文档描述:
Methods to Override
If you are creating a concurrent operation, you need to override the following methods and properties at a minimum:
start
asynchronous
executing
finished