C语言 Blocks

  • 无参数无返回值的闭包
void (^printMessage)(void) = ^(void){
            NSLog(@"This is Blocks Log");
};
        
printMessage(); // This is Blocks Log
  • 参数
#import 

void (^paramMethod)(int,int) = ^(int a,int b) {
    NSLog(@"a: %d ,b: %d ",a,b);
};

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        paramMethod(1,2); // a: 1 ,b: 2
        
    }
    return 0;
}
  • 返回值
#import 

int (^addMethod)(int,int) = ^(int a,int b) {
    int sum = a + b;
    return sum;
};

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        int result =  addMethod(1,2);
        NSLog(@"result: %d",result); // result: 3
    }
    return 0;
}

⚠️ blocks只能获取在函数之前定义的变量,不能获取之后的值

int f = 10;
        
void (^printF)(void) = ^(void){
      NSLog(@"f : %d",f);
};
        
f = 12;
        
printF(); // f : 10

⚠️ 不能在blocks语句中更改函数之前的变量否则或报错

图.png
__block int f = 10;
        
void (^printF)(void) = ^(void){
    NSLog(@"f1 : %d",f); // f1 : 12
    f = 20;
};
        
f = 12;
        
printF();
NSLog(@"f2 : %d",f); // f2 : 20

你可能感兴趣的:(C语言 Blocks)