OC:Block书写

2018-12-23  本文已影响8人  春暖花已开
作为本地变量:

格式:

returnType (^blockName)(paramType param...) = ^returnType(paramType param...) {
    return ...
};

例如:

NSInteger (^getSum)(NSInteger a, NSInteger b) = ^NSInteger(NSInteger a, NSInteger b) {
        return a + b;
};
NSLog(@"%ld", getSum(1, 2));  //打印3

作为属性

格式:

@property (nonatomic, copy) returnType (^blockName)(paramType param); 

例如:

@property (nonatomic, copy) void (^blockName)(NSString *paramName);

作为方法参数

格式:

- (void)someMethodThatTakesABlock:(returnType (^)(paramType param))blockName;

例如:

- (void)doSomethingWithBlock:(void(^)(NSString *name))block {
    
}

用作typedef

格式:

typedef returnType (^TypeName)(paramType param);
TypeName blockName = ^returnType(parameters) {...};

例如:

typedef NSInteger (^GetSumWithDef)(NSInteger a, NSInteger b);
GetSumWithDef block = ^NSInteger(NSInteger a, NSInteger b) {
        return a + b;
};
NSLog(@"%ld", block(2, 2)); //打印4
上一篇 下一篇

猜你喜欢

热点阅读