block :是一个指向结构体的指针。可暂时保存代码块。
1.带参数or返回值
// 1.带参数的block
void (^oneblock)(int) = ^(int numberLine){ // 存储代码
for (int i = 0; i < numberLine; i++) {
NSLog(@"****");
}
};
oneblock(3);
// 2.带返回值的block
int (^twoblock)() = ^{
int a = 10, b = 10;
return a + b;
};
int twoblockResult = twoblock();
NSLog(@"result = %d", twoblockResult);
// 3.带参数和返回值
int (^threeblock)(int, int) = ^(int a, int b ){
return a + b;
};
int threeblockResult = threeblock(1024,1024);
NSLog(@"threeblockResult = %d", threeblockResult);
2.typedef简化声明
typedef int (^typedefBlock)(int, int);
void testtypedefBlock()
{
typedefBlock result = ^(int a, int b){
return a + b;
};
int typedefresult = result(10, 10);
NSLog(@"typedefresult = %d",typedefresult );
}
3.block参数传递
void gotowork(void (^mytodaywork)())
{
NSLog(@"起床");
mytodaywork();
NSLog(@"回家");
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
gotowork(^{
NSLog(@"去公司熟悉下代码");
});
gotowork(^{
NSLog(@"完成实现功能");
});
}
return 0;
}