OC定义Block的四种形式

2021-08-19  本文已影响0人  大成小栈

脱离Xcode直接手写一个Block,很多时候还真不一定每次都写得对。
常用定义形式共有以下几种:

// 宏定义Block
typedef NSString* (BlockName)(NSString *param1, NSString *param2);
BlockName block = ^NSString* (NSString *param1, NSString *param2){
    ...
    return...
};

// 声明一个局部Block
NSString * (BlockName)(NSString *param) = ^ NSString* (NSString *param){
    ...
    return...
};

// 声明一个Block属性变量
@property (nonatomic, copy)  NSString * ( ^BlockName )(NSString *param1, NSString *param2);

// Block作为方法的入参数
- (void) someMethodThatTakesBlock:( NSString * (^)(NSString *param) )block;

// Block作为方法的回调对象
[someObj someMethodThatTakesBlock: ^ (NSString *param){
    ... 
    // void型block,无返回值
}];

链式调用中的block:

//// .h
@interface CustomView : UIView

+ (CustomView *)initCustomView:(void(^)(CustomView *custom))block;

- (CustomView *(^)(CGRect))viewFrame;
- (CustomView *(^)(UIColor *))viewColor;

@end

//// .m
@implementation CustomView

+ (CustomView *)initCustomView:(void (^)(CustomView * _Nonnull))block {
    
    CustomView *custom = [[CustomView alloc] init];
    
    if (block) {
        block(custom);
    }
    return custom;
}

- (CustomView *(^)(CGRect))viewFrame {

    CustomView *(^frameBlock)(CGRect frame) = ^CustomView *(CGRect frame){
        self.frame = frame;
        return self;
    };
    
    return frameBlock;
    
    
    return ^CustomView *(CGRect frame){
        self.frame = frame;
        return self;
    };
}

- (CustomView *(^)(UIColor *))viewColor {
    return ^CustomView *(UIColor *color){
        self.backgroundColor = color;
        return self;
    };
}
@end
上一篇 下一篇

猜你喜欢

热点阅读