iOS block源码分析
程序员文章站
2022-04-08 22:49:09
...
创建一个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;
};