operation 对象定期地调用 isCancelled 方法,如果返回YES(表示已取消),则立即退出执行。不管是自定义 NSOperation 子类,还是使用系统提供的两个具体子类,都需要支持取消。isCancelled方法本身非常轻量,可以频繁地调用而不产生大的性能损失。
以下地方可能需要调用isCancelled:
在执行任何实际的工作之前;
在循环的每次迭代过程中,如果每个迭代相对较长可能需要调用多次;
代码中相对比较容易中止操作的任何地方
- - (void)main
- {
- @try
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- BOOL isDone = NO;
- while (![self isCancelled] && !isDone) {
- // Do some work and set isDone to YES when finished
- }
- [pool release];
- }
- @catch(...)
- {
- // Do not rethrow exceptions.
- }
- }
为并发执行配置operations
Operation对象默认按同步方式执行,也就是在调用start方法的那个线程中直接执行。由于operation queue为非并发operation提供了线程支持,对应用来说,多数operations仍然是异步执行的。
但是如果你希望手工执行operations,而且仍然希望能够异步执行操作,你就必须采取适当的措施,通过定义operation对象为并发操作来实现。
| 方法 | 描述 |
| start | (必须)所有并发操作都必须覆盖这个方法,以自定义的实现替换默认行为。手动执行一个操作时,你会调用start方法。因此你对这个方法的实现是操作的起点,设置一个线程或其它执行环境,来执行你的任务。你的实现在任何时候都绝对不能调用super。 |
| main | (可选)这个方法通常用来实现operation对象相关联的任务。尽管你可以在start方法中执行任务,使用main来实现任务可以让你的代码更加清晰地分离设置和任务代码 |
| isExecuting isFinished |
(必须)并发操作负责设置自己的执行环境,并向外部client报告执行环境的状态。因此并发操作必须维护某些状态信息,以知道是否正在执行任务,是否已经完成任务。使用这两个方法报告自己的状态。 这两个方法的实现必须能够在其它多个线程中同时调用。另外这些方法报告的状态变化时,还需要为相应的key path产生适当的KVO通知。 |
| isConcurrent | (必须)标识一个操作是否并发operation,覆盖这个方法并返回YES |
- @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;
- }
- //必须重载
- //为相应的key path产生适当的KVO通知
- //[self willChangeValueForKey:@"isFinished"];
- //finished = YES;
- //[self didChangeValueForKey:@"isFinished"];
- - (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
- {
- NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
- // Do the main work of the operation here.
- [self completeOperation];
- [pool release];
- }
- @catch(...)
- {
- // Do not rethrow exceptions.
- }
- }
- - (void)completeOperation
- {
- //为相应的key path产生适当的KVO通知
- [self willChangeValueForKey:@"isFinished"];
- [self willChangeValueForKey:@"isExecuting"];
- executing = NO;
- finished = YES;
- [self didChangeValueForKey:@"isExecuting"];
- [self didChangeValueForKey:@"isFinished"];
- }
- @end
