NSInteger count = 10;
NSInteger(^sum)(void)=^{
return count;
};
count = 20;
NSLog(@"\\n %ld",sum()); // 结果:10
__block NSInteger block_count = 10;
NSInteger(^block_sum)(void)=^{
return block_count;
};
block_count = 20;
NSLog(@"\\n %ld",block_sum()); //结果:20
NSMutableString *mutable_string = [NSMutableString stringWithString:@"aaa"];
void(^mutable_append)(void)=^{
[mutable_string appendString:@"ccc"];
};
[mutable_string appendString:@"bbb"];
mutable_append();
NSLog(@"\\n %@",mutable_string); //结果:aaabbbccc
NSString *string = @"aaa";
NSString*(^append)(void)=^{
return [string stringByAppendingString:@"ccc"];
};
string = @"bbb";
NSLog(@"\\n %@",append()); //结果:aaaccc
__block NSString *block_string = @"aaa";
NSString*(^block_append)(void)=^{
return [block_string stringByAppendingString:@"ccc"];
};
block_string = @"bbb";
NSLog(@"\\n %@",block_append()); //结果: bbbccc
结论是:
没有使用“__block”时,内部是直接使用了该变量,对于值类型变量是直接定义新变量并赋值相同,对于引用类型变量是定义一个新变量并copy它。
当使用“__block”时,会增加一个结构体将变量包起来,对于值类型变量就相当于变成指针,对于引用类型相当于变成了指针的指针。