重写start
方法来自定义NSOpeartion
- 子类化视图控制器
@interface MyOperation : NSOperation
@end
- 子类为原来的
executing
属性和finished
属性添加setter方法和设置属性名
@interface MyOperation()
@property (assign, readonly, getter=isExecuting) BOOL executing;
@property (assign, readonly, getter=isFinished) BOOL finished;
@end
@implementation MyOperation
@synthesize executing = _executing;
@synthesize finished = _finished;
@end
- 重写setter方法,手动发送kvo监听executing的getter方法
isExecuting
和finished
的isFinished
。
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
4.开始执行的时候设置 self.finished = NO; self.executing = YES; 结束的时候设置 self.finished = YES; self.executing = NO
5.和main方法一样,添加self.isCanceled判断
Demo
#import "MyOperation.h"
@interface MyOperation()
@property (assign, readonly, getter=isExecuting) BOOL executing;
@property (assign, readonly, getter=isFinished) BOOL finished;
@end
@implementation MyOperation
@synthesize executing = _executing;
@synthesize finished = _finished;
- (void)start {
if (self.isCancelled) {
self.finished = YES;
self.executing = NO;
}
self.finished = NO;
self.executing = YES;
[self doSomething];
}
- (void)doSomething {
for (NSInteger i = 0; i < 100; i++) {
NSLog(@"%ld", i);
}
self.finished = YES;
self.executing = NO;
}
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
@end
start与main方法区别
前者比后者更加灵活,通过operation
标记状态来告知queue是否要将自己移除,在
start中开了新线程后,可以在新线程的方法中标记状态。而
main一定是
main```执行完后自动从队列中移除。
网友评论