http://www.cocoachina.com/bbs/read.php?tid-1709563.html
http://www.jianshu.com/p/3309b0c0cab3
同步或异步
默认的NSOperation是同步执行的,当start以后isExecuting会变成YES,然后立即执行main,当main返回后,isExecuting会设为NO并且isFinished会设为YES。
当你需要一个异步的Operation,那么重载start方法否则main就可以了。异步的Operation需要重载isExecuting和isFinished的getter,需要手动控制Operation的状态,不然当main返回后Operation会直接将isFinished设为YES。。。Operation就挂掉了。
其实异步的Operation是否重载main也没有关系,重载也没有什么意义就是了,因为状态都是手动控制的。
至于isConcurrent,现在则推荐isAsynchronous,我不太明确这两个的意义,因为我没见过系统会调用。可能只是一个flag,当你的自定义Operation是异步执行的就应该设置为YES,外部判断的时候可以知道,类似君子约定。。。
自定义的话看这里
http://www.jianshu.com/p/3309b0c0cab3
1 NSOperation子类
@interface Operation ()
@property (nonatomic, assign, getter=isExecuting) BOOL executing;
@property (nonatomic, assign, getter=isFinished) BOOL finished;
@end
@implementation Operation
@synthesize finished = _finished, executing = _executing;
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
- (void)start {
if (self.isCancelled) {
self.finished = YES;
return;
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 这里开始异步
// 如果用非同步的网络请求,这里没有必要手动添加到异步队列
// 当任务完成是需要修改finished和executing
self.finished = YES;
self.executing = NO;
});
self.executing = YES;
}
/**
//是否同步
- (BOOL)isAsynchronous{
return YES;
}
**/
@end
2 调用
-(void)cell:(TableViewCell *)cell item:(FileInfo *)item indexPath:(NSIndexPath *)indexPath{
//补全video信息
ViodeInfoTask *task = self.operationTaskCache[item.name];
if (!task) {
//初始化任务
task = [[ViodeInfoTask alloc] initWithFileInfo:item];
// 进行缓存
self.operationTaskCache[item.name] = task;
// 添加操作
[self.queue addOperation:task];
//任务结束后炒作
[task setCompletionBlock:^{
NSLog(@"任务结束:%@" , item.name);
// 回主线程展示
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//刷新cell数据
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
// 下载完成,移除操作
[self.operationTaskCache removeObjectForKey:item.name];
}];
}];
}