美文网首页Effective Objective-C 2.0
📚Effective OC - Tip39,40 用 bloc

📚Effective OC - Tip39,40 用 bloc

作者: 小万叔叔 | 来源:发表于2017-01-10 19:42 被阅读7次

    着重说一下 block 的应用场景,为什么大家都愿意用 block :

    • 直观,简洁,可以方便的在一个场景里面使用,并可以捕获当前的变量。
    //case 1可以声明不同语义
    //.h
    typedef void(^CompletesBlock)(int status);
    typedef void(^ErrorBlock)(int status);
    typedef void(^FailedBlock)(int status);
    typedef void(^ProgressBlock)(int status);
    - (void)doSomething:(CompletesBlock)completeBlock failed:(FailedBlock)failedBlock;
    //.m 
    - (void)doSomething:(CompletesBlock)completeBlock failed:(FailedBlock)failedBlock {
        if (completeBlock){
            completeBlock(1);
            completeBlock = nil;
        }
        if (failedBlock) {
            failedBlock(0);
            failedBlock = nil;
        }
    }
    //调用
        BlockHandler *handler = [BlockHandler new];
        //case 1
        [handler doSomething:^(int status) {
                    NSLog(@"handler success %@", @(status));
                        }failed:^(int status) {
                          NSLog(@"handler failed %@", @(status));
                     }];
    
            //case 2
        handler.completeBlock = ^(int status) {
            NSLog(@"handler success 2");
        };
        handler.failedBlock = ^(int status) {
            NSLog(@"handler failed 2");
        };
        [handler innerDoSomething];
    
    • 可以指定调用的Queue
    //.m
    - (void)addBlock:(NSOperationQueue *)queue block:(void (^)(int))block {
        [queue addOperationWithBlock:^{
            if (block) {
                block(1);
            }
        }];
    }
    
    //调用
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [handler addBlock:queue block:^(int i) {
        NSLog(@"add block on queue %@", @(i));
    }];
    

    相关文章

      网友评论

        本文标题:📚Effective OC - Tip39,40 用 bloc

        本文链接:https://www.haomeiwen.com/subject/dvhlbttx.html