Block的本质
block本质上也是一个OC对象,它内部也有个isa指针
void (^block)(void) = ^{
NSLog(@"I am a block");
};
block();
以上OC代码生成的C++代码为:
//block的定义声明
void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
//block的调用
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
其中的生成的C++结构体分别是:
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
struct __block_impl {
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
static struct __main_block_desc_0 {
size_t reserved;
size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};
代码块生成为函数
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
NSLog(...);
}
- block最后生成的是结构体__main_block_impl_0,
- block是封装了函数调用以及函数调用环境的OC对象
- 底层结构如下图所示:
Blcok_Layout | 备注 |
---|---|
(void *) isa | isa指针 |
(int) flags | |
int Reserved | |
void *FuncPtr | 函数地址 |
struct __main_block_desc_0* Desc | block对象信息 |
__main_block_desc_0 | 备注 |
---|---|
reserved | |
Block_size | block结构体大小 |
网友评论