- 无参数无返回值的闭包
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
图.png⚠️ 不能在blocks语句中更改函数之前的变量否则或报错
__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
网友评论