__block类型变量的实现

static int static_i = 2000;


int local_i = 100;

__block int a = 1;
__block NSObject *obj = [[NSObject alloc] init];

void (^block)(void)= ^(void){
   local_i;
   static_i;
   a--;
   obj;
};
block();

a++;
obj;

clang -rewrite-objc -fobjc-arc main.m

//__block int a
struct __Block_byref_a_0 {
 void *__isa;
 __Block_byref_a_0 *__forwarding;
 int __flags;
 int __size;
 int a;
};

//__block NSObject *obj
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;
};

//block结构体
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;

  //捕获到的局部变量
  __Block_byref_a_0 *a; // by ref
  __Block_byref_obj_1 *obj; // by ref
  int local_i;

  __main_block_impl_0(
    void *fp, 
    struct __main_block_desc_0 *desc, 
    int _local_i,
    __Block_byref_a_0 *_a, 
    __Block_byref_obj_1 *_obj,
    int flags=0) : local_i(_local_i), a(_a->__forwarding), obj(_obj->__forwarding) {
      impl.isa = &_NSConcreteStackBlock;
      impl.Flags = flags;
      impl.FuncPtr = fp;
      Desc = desc;
  }
};

//block - fp
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  __Block_byref_a_0 *a = __cself->a; // bound by ref
  __Block_byref_obj_1 *obj = __cself->obj; // bound by ref
  int local_i = __cself->local_i; // bound by copy

  local_i;
  static_i;

  (a->__forwarding->a)--;
  (obj->__forwarding->obj);
}

//此处省略若干代码

//__block int a = 1
__attribute__((__blocks__(byref))) __Block_byref_a_0 a = 
{(void*)0, (__Block_byref_a_0 *)&a,  0,  sizeof(__Block_byref_a_0), 1};

//__block NSObject *obj = [[NSObject alloc] init];
__attribute__((__blocks__(byref))) __Block_byref_obj_1 obj = 
{(void*)0, (__Block_byref_obj_1 *)&obj,  33554432,  sizeof(__Block_byref_obj_1), 
__Block_byref_id_object_copy_131, 
__Block_byref_id_object_dispose_131, 
((NSObject *(*)(id, SEL))(void *)objc_msgSend)((id)((NSObject *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSObject"), sel_registerName("alloc")), sel_registerName("init"))};

void (*block)(void)= ((void (*)())&__main_block_impl_0(
  (void *)__main_block_func_0, 
  &__main_block_desc_0_DATA, 
  local_i,
  (__Block_byref_a_0 *)&a, 
  (__Block_byref_obj_1 *)&obj, 
  570425344))();

((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);

(a.__forwarding->a)++;
(obj.__forwarding->obj);

__forwarding

  • Block没有执行过copy时,__forwarding指向自己

  • Block执行过copy后,栈与堆中的block_ref_obj.__forwarding都指向堆中的block_ref

结论

未加__block修饰符时,传递给block的是值
带有__block修饰符时,传递给block的是Block_byref类型的指针

你可能感兴趣的:(__block类型变量的实现)