Objective-C 闭包声明(Block)

本地变量

返回类型(^block名称)(参数类型列表) = ^返回类型(参数) {代码段};
//举例 example 
    NSString *(^blockName)(NSString *) = ^NSString *(NSString *a){
        NSLog(@"%@", a);
        return a;
    };
    NSString *test = blockName(@"test");
    NSLog(@"%@", test);

属性

@property (nonatomic, copy, nullability) 返回类型 (^block名称)(参数类型列表);
//举例 example
@property (nonatomic, copy) NSString *(^blockName)(NSString *);

方法参数

- (void)someMethodThatTakesABlock:(返回类型 (^)(参数列表))block名称;
//举例
- (void)someMethodThatTakesABlock:(NSString * (^)(NSString *))blockName;

方法调用传参

[someObject someMethodThatTakesABlock:^返回类型 (参数名) {代码段}];
//举例
[someObject someMethodThatTakesABlock:^NSString * (NSString *test) {NSLog(@"%@", test);}];

C函数参数

void SomeFunctionThatTakesABlock(返回类型 (^block名称)(参数名称列表));
//例子
void SomeFunctionThatTakesABlock(NSString * (^blockName)(NSString *)); 

类型定义

typedef 返回类型 (^Block类型名称)(参数类型列表);
Block类型名称 block名称 = ^返回类型(参数列表) {代码段};
//例子
typedef NSString * (^TypeName)(NSString *);
TypeName blockName = ^NSString *(NSString *test) {NSLog(@"%@", test);};

你可能感兴趣的:(Objective-C 闭包声明(Block))