__block修饰符
2020-07-17 本文已影响0人
it小小菜鸟
1. __block可以用于解决block内部无法修改auto变量值的问题
2. __block不能修饰全局变量、静态变量(static)
3. __block修饰变量时,编译器会把该变量包装成一个对象
// OC代码
__block int age = 10;
__block NSObject *obj = [[NSObject alloc] init];
void (^block1)(void) = ^{
age = 20;
obj = nil;
NSLog(@"block a = %d",age);
};
//修饰基本数据类型,外部变量用__block修饰之后的结构体
struct __Block_byref_age_0 {
void *__isa;
__Block_byref_age_0 *__forwarding;
int __flags;
int __size;
int age;
};
// 修饰类
struct __Block_byref_obj_1 {
void *__isa;
__Block_byref_obj_1 *__forwarding;
int __flags;
int __size;
void (*__Block_byref_id_object_copy)(void*, void*);
void (*__Block_byref_id_object_dispose)(void*);
NSObject *__strong obj;
};
static struct __main_block_desc_0 {
size_t reserved;
size_t Block_size;
void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
// 捕获__block修饰的外部变量之后的 Block结构体
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__Block_byref_age_0 *age; // by ref
__Block_byref_obj_1 *obj; // by ref
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_age_0 *_age, __Block_byref_obj_1 *_obj, int flags=0) : age(_age->__forwarding), obj(_obj->__forwarding) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};