OC Block 的N种写法

Block的写法经常忘记,或者记忆不是很清楚。 特地整理一下帮助大家作为辅助记忆
希望能帮到大家

关键字:block block写法

Block 的写法汇总

声明属性

@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

/// block
@property (nonatomic, strong) void(^blcokProperty)(void);
/// 带参数的block
@property (nonatomic, copy) UIViewController *(^blockPropertyParam)(NSObject *);

方法入参声明

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

- (void)methodWithBlock:(void(^)(void))block{
    /// method block
}

- (void)methodWithBlockAndParam:(UIViewController *(^)(NSObject *))block{
    /// method with param block
}

方法入参

[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];

    /// 调用带无参数的Block
    [self methodWithBlock:^{
        NSLog(@"do nothong");
    }];
    
    ///  调用带参数的Block,
    [self methodWithBlockAndParam:^UIViewController *(NSObject *obj) {
        return [UIViewController new];
    }];
    ///  声明中的返回参数声明, 调用的时候可以省略
    [self methodWithBlockAndParam:^(NSObject *obj) {
        return [UIViewController new];
    }];

C函数中入参写法

void SomeFunctionThatTakesABlock(returnType (^blockName)(parameterTypes));

/// c函数的定义
void cFunctionDefine(void(^cBlock)(void)){
    cBlock();
}

/// c函数的定义 block 带参数
void cFunctionWithParam(UIViewController *(^cBlock)(NSObject *)){
    cBlock([NSObject new]);
}

/// 调用
cFunctionDefine(^{
        
});
cFunctionWithParam(^UIViewController *(NSObject *obj) {
    return [UIViewController new];
});

声明一个类型

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

typedef void(^BlockTypedef)(void);
typedef UIViewController *(^BlockTypedefParam)(NSObject *);

/// 使用typedefine 定义的block
@property (nonatomic, copy) BlockTypedef blockTypedef;
/// 使用typedefine 定义的带参block
@property (nonatomic, copy) BlockTypedefParam blockTypedefParam;

- (void)methodWithBlockTypedef:(BlockTypedef)block{
    /// method blcok with typedef
}

- (void)methodWithBlockTypedefAndParam:(BlockTypedefParam)block{
    ///  method with param block with typedef
}

- (BlockTypedef)methodReturnBlock{
    return ^{
        /// return a block
    };
}

- (BlockTypedefParam)methodReturnBlockParam{
    return ^(NSObject *obj){
        return [UIViewController new];
    };
}
- (BlockTypedefParam)methodReturnBlockParam01{
    return ^UIViewController *(NSObject *obj){
        return [UIViewController new];
    };
}

参考资料

  • 国外小哥写的Block用法

你可能感兴趣的:(OC Block 的N种写法)