block和variable
1、本地变量与block的关系及其变化
int main(int argc, const char * argv[]) {
@autoreleasepool {
int a = 10;
int b = 20;
NSLog(@"&a:%p ,&b:%p ,a:%d ,b:%d",&a,&b,a,b);
//&a:0x7ffeefbff63c ,&b:0x7ffeefbff638 ,a:10 ,b:20
int (^block)(void) = ^(void)
{
NSLog(@"&a:%p ,&b:%p ,a:%d ,b:%d",&a,&b,a,b);
//&a:0x1005035f0 ,&b:0x1005035f4 ,a:10 ,b:20
//疑问 1:为什么代码块里面的a和b的地址改变了?
//a = 12; 如果这样做会报错
//b = 13; 如果这样做会报错
//疑问 3:为什么在block内部修改不了a,b的值?
//int *p = (int *)&a; //疑问 4:为什么这样的修改成功了?
//*p = 12;
return a + b;
};
NSLog(@"&a:%p ,&b:%p ,a:%d ,b:%d",&a,&b,a,b);
//&a:0x7ffeefbff63c ,&b:0x7ffeefbff638 ,a:10 ,b:20
NSLog(@"%d",block()); //30
a = 11;
b = 22;
NSLog(@"&a:%p ,&b:%p ,a:%d ,b:%d",&a,&b,a,b);
//&a:0x7ffeefbff63c ,&b:0x7ffeefbff638 ,a:11 ,b:22
NSLog(@"%d",block()); //30
//疑问 2:为什么a和b的外部值改变了没有影响代码块里的?
}
return 0;
}
转换后的cpp代码
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
int a = 10;
int b = 20;
NSLog((NSString *)&__NSConstantStringImpl__var_folders_sz_wcgbthq12mv1dp_m892vbz000000gn_T_main_c15216_mi_0,&a,&b,a,b);
//输出的是&a,&b,a,b
int (*block)(void) = ((int (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, a, b));
//填充__main_block_impl_0结构体,__main_block_func_0为block代码实现函数,
//__main_block_desc_0_DATA为描述block的结构体变量
//注意这里a,b是传值
NSLog((NSString *)&__NSConstantStringImpl__var_folders_sz_wcgbthq12mv1dp_m892vbz000000gn_T_main_c15216_mi_2,&a,&b,a,b);
//输出的是&a,&b,a,b
NSLog((NSString *)&__NSConstantStringImpl__var_folders_sz_wcgbthq12mv1dp_m892vbz000000gn_T_main_c15216_mi_3,((int (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block));
//利用FuncPtr指针调用__main_block_func_0函数
a = 11;
b = 22;
NSLog((NSString *)&__NSConstantStringImpl__var_folders_sz_wcgbthq12mv1dp_m892vbz000000gn_T_main_c15216_mi_4,&a,&b,a,b);
//输出的是&a,&b,a&#x