欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS block源码分析

程序员文章站 2022-04-08 22:49:09
...

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

创建一个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文件
iOS block源码分析
搜索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的本质<二>

相关标签: ios 面试