Effective Objective-C 2.0

📚Effective OC - Tip39,40 用 bloc

2017-01-10  本文已影响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];
//.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));
}];
上一篇 下一篇

猜你喜欢

热点阅读