美文网首页
Objective-C的Block实质与实现探究 part-6

Objective-C的Block实质与实现探究 part-6

作者: KardelShaw | 来源:发表于2017-01-04 01:31 被阅读0次

Block使用__block�变量,且该变量为对象的情况

</br>

typedef void (^blk_t)(id);

blk_t blk;

{
    __block id array = [[NSMutableArray alloc] init];
    blk = [^(id obj) {
        
        [array addObject: obj];

        NSlog(@"array count = %ld", [array count]);

    } copy];
}

blk([[NSObject alloc] init]);
blk([[NSObject alloc] init]);
blk([[NSObject alloc] init]);

转换为C++:

struct __Block_byref_obj_0 {
    void *__isa;
    __Block_byref_obj_0 *__forwarding;
    int __flags;
    int __size;
    void (*__Block_byref_id_object_copy)(void *, void *);
    void (*__Block_byref_id_object_dispose)(void *);
    __strong id obj;
};

static void __Block_byref_id_object_copy_131(void *dst, void *src) {
    _Block_object_assign((char *)dst + 40, *(void **)((char *)src + 40), 131);
}

static void __Block_byref_id_object_dispose_131(void *src) {
    _Block_object_dispose(*(void **) ((char *)src + 40), 131);
}

__Block_byref_obj_0 = {
    0,
    &obj,
    0x2000000,
    sizeof(__Block_byref_obj_0),
    __Block_byref_id_object_copy_131,
    __Block_byref_id_object_dispose_131,
    [[NSObject alloc] init]
};

虽然与截获对象时和使用__block变量时的代码稍有不同,但仍看到有copy函数和dispose函数。所以Block从栈复制到堆上时,对有__block修饰符的对象也会被复制到堆上。

相关文章

网友评论

      本文标题:Objective-C的Block实质与实现探究 part-6

      本文链接:https://www.haomeiwen.com/subject/zrqovttx.html