iOS block源码分析

返回上级目录:iOS面试和知识点整理

官方文档连接:
Working with Blocks(Programming With Objective-C)

创建一个XXBlock类

#import "XXBlock.h"

@implementation XXBlock

- (void)test {
    int a = 10;
    void (^block)(void) = ^{
        NSLog(@"%d",a);
    };
    block();
}

@end

打开终端,cd到XXBlock.m所在的文件夹,执行命令
clang -rewrite-objc XXBlock.m会得到一个XXBlock.cpp文件
在这里插入图片描述
搜索XXBlock,可以看到如下的代码实现

// @implementation XXBlock


struct __XXBlock__test_block_impl_0 {
  struct __block_impl impl;
  struct __XXBlock__test_block_desc_0* Desc;
  int a;
  __XXBlock__test_block_impl_0(void *fp, struct __XXBlock__test_block_desc_0 *desc, int _a, int flags=0) : a(_a) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __XXBlock__test_block_func_0(struct __XXBlock__test_block_impl_0 *__cself) {
  int a = __cself->a; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_p9_pnn1xm8135q5cvcdpwg7clwc0000gn_T_XXBlock_adfd56_mi_0,a);
    }

static struct __XXBlock__test_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __XXBlock__test_block_desc_0_DATA = { 0, sizeof(struct __XXBlock__test_block_impl_0)};

static void _I_XXBlock_test(XXBlock * self, SEL _cmd) {
    int a = 10;
    void (*block)(void) = ((void (*)())&__XXBlock__test_block_impl_0((void *)__XXBlock__test_block_func_0, &__XXBlock__test_block_desc_0_DATA, a));
    ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}

// @end

__block_impl的内部实现
看到isa,证明block的本质是一个对象

struct __block_impl {
  void *isa;//看到isa,证明block的本质是一个对象
  int Flags;
  int Reserved;
  void *FuncPtr;
};

参考博客:
iOS-Block源码分析
iOS源码解析:Block的本质<一>
iOS源码解析:Block的本质<二>

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页