iOS底层基础知识iOS开发那些事

iOS-底层原理(10)-block-__block属性详解

2018-09-01  本文已影响64人  路飞_Luck

__block修饰符

结构图如下

结构图.png
__block的本质

代码佐证

// 定义一个block
typedef void (^CSBlock) (void);

// block内部实现
struct __Block_byref_age_0 {
    void *__isa;
    struct __Block_byref_age_0 *__forwarding;
    int __flags;
    int __size;
    int age;
};

struct __main_block_desc_0 {
    size_t reserved;
    size_t Block_size;
    void (*copy)(void);
    void (*dispose)(void);
};

struct __block_impl {
    void *isa;
    int Flags;
    int Reserved;
    void *FuncPtr;
};

struct __main_block_impl_0 {
    struct __block_impl impl;
    struct __main_block_desc_0* Desc;
    struct __Block_byref_age_0 *age;
};

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        __block int age = 10;
        
        CSBlock block = ^{
            age = 20;
            NSLog(@"age is %d", age);
        };
        
        struct __main_block_impl_0 *blockImpl = (__bridge struct __main_block_impl_0 *)block;
        
        NSLog(@"%p", &age);
    }
    return 0;
}
image.png

可知外界访问age,实际上在block内部是访问结构体__Block_byref_age_0中的age变量

__block的内存管理
image.png image.png image.png

对象类型的auto变量、__block变量 异同

__block变量(假设变量名叫做a)
_Block_object_assign((void*)&dst->a, (void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);

对象类型的auto变量(假设变量名叫做p)
_Block_object_assign((void*)&dst->p, (void*)src->p, 3/*BLOCK_FIELD_IS_OBJECT*/);

__block变量(假设变量名叫做a)
_Block_object_dispose((void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);

对象类型的auto变量(假设变量名叫做p)
_Block_object_dispose((void*)src->p, 3/*BLOCK_FIELD_IS_OBJECT*/);

image.png
__block的__forwarding指针
被__block修饰的对象类型

代码实现如下

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 演示被__block修饰的变量类型
        // 1.有__weak修饰
        CSBlock block;
        {
            Person *person = [[Person alloc] init];
            __block __weak Person *weakPerson = person;
            block = ^ {
                NSLog(@"%p",weakPerson);
            };
        }
        block();
    }
    return 0;
}

运行结果

image.png
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 演示被__block修饰的变量类型
        // 1.有__weak修饰
        CSBlock block;
        {
            Person *person = [[Person alloc] init];
            __block Person *weakPerson = person;
            block = ^ {
                NSLog(@"%p",weakPerson);
            };
        }
        block();
    }
    return 0;
}

运行结果


image.png
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 3.MRC环境下
        Person *person = [[Person alloc] init];
        
        CSBlock block = [^{
            NSLog(@"%p", person);
        } copy];
        
        [person release];
        
        block();
        
        [block release];
    }
    return 0;
}
image.png

本文参考借鉴MJ的教程视频,非常感谢.


项目演示代码
iOS-block-__block的本质


更多block相关文章

iOS-block底层原理详解-本质,类型,copy属性

iOS-copy底层原理之auto变量

iOS-block底层原理之循环引用详解

上一篇下一篇

猜你喜欢

热点阅读