Block

Block是一个对象,它封装了block的函数和函数执行上下文。

void testBlock() {
    
    int num = 3;
    void(^block)(int) = ^(int i){
        NSLog(@"%d", i * num);
    };
    block(2);
}

clang -rewrite-objc main.m 查看main.cpp

void testBlock() {

    int num = 3;
    void(*block)(int) = ((void (*)(int))&__testBlock_block_impl_0((void *)__testBlock_block_func_0, 
                          &__testBlock_block_desc_0_DATA, num));
    ((void (*)(__block_impl *, int))((__block_impl *)block)->FuncPtr)((__block_impl *)block, 2);
}
block封装而成的结构体

结构体__testBlock_block_impl_0的构造方法内有isa指针,也可以说block最后封装成了一个对象。

struct __testBlock_block_impl_0 {
  struct __block_impl impl;
  struct __testBlock_block_desc_0* Desc;
  int num;
  // 构造函数。fp表示方法指针,指向__testBlock_block_func_0。
  __testBlock_block_impl_0(void *fp, struct __testBlock_block_desc_0 *desc, int _num, int flags=0) : num(_num) {
    //block的类型。NSConcreteGlobalBlock,NSConcreteStackBlock,NSConcreteMallocBlock
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};
block内容封装而成的函数
static void __testBlock_block_func_0(struct __testBlock_block_impl_0 *__cself, int i) {
  int num = __cself->num; // bound by copy
  NSLog((NSString *)&__NSConstantStringImpl__var_folders_8q_dqmgnrnj4g3cmnwws_kp_8sr0000gn_T_main_b72911_mi_0, i * num);
}
block的描述
static struct __testBlock_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __testBlock_block_desc_0_DATA = { 0, sizeof(struct __testBlock_block_impl_0)};

你可能感兴趣的:(Block)