NSOperation 异步 或 同步 实例

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];
                }];
                
            }];
        }


 

转载于:https://my.oschina.net/huqiji/blog/870997

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值