Block是一個對象,它封裝了block的函數(shù)和函數(shù)執(zhí)行上下文。
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封裝而成的結(jié)構(gòu)體
結(jié)構(gòu)體__testBlock_block_impl_0的構(gòu)造方法內(nèi)有isa指針,也可以說block最后封裝成了一個對象。
struct __testBlock_block_impl_0 {
struct __block_impl impl;
struct __testBlock_block_desc_0* Desc;
int num;
// 構(gòu)造函數(shù)。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內(nèi)容封裝而成的函數(shù)
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)};