C语言 Blocks

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

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 <Foundation/Foundation.h>

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容