1. block捕捉变量:
结论:只有调用_Block_copy 才能持有截获的附有 __strong 修饰符的对象类型的自动变量值。
block 中使用对象类型的自动变量时,除以下情形,推荐使用copy方法:
- “When the Block is returned from a function
- When the Block is assigned to a member variable of id or the Block type class, with a __strong qualifier
- When the Block is passed to a method, including “usingBlock” in the Cocoa Framework, or a Grand Central Dispatch API”
blk_t blk 执行copy情况:
blk_t blk;
{
id array = [[NSMutableArray alloc] init];
blk = [^(id obj) {
[array addObject:obj];
NSLog(@"array count = %ld", [array count]);
} copy];
}//由于copy,所以block持有array,所以超出作用域依然存在
blk([[NSObject alloc] init]); //array count = 1
blk([[NSObject alloc] init]); //array count = 2
blk([[NSObject alloc] init]); //array count = 3
blk_t blk 不执行copy情况:
{
id array = [[NSMutableArray alloc] init];
blk = ^(id obj) {
[array addObject:obj];
NSLog(@"array count = %ld", [array count]);
};
}
//超出id 作用域,_ _strong 修饰的对象被释放。
blk([[NSObject alloc] init]); //outPut:程序强行结束。
blk([[NSObject alloc] init]);
blk([[NSObject alloc] init]);”