Block底层原理

底层数据结构

创建一个命令行项目,在main函数中定义一个Block并进行调用

#import 
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        void (^block)(void) = ^{
            NSLog(@"Hello World !");
        };
        block();
    }
    return 0;
}

在控制台中输入:xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m 将OC代码转为C++代码

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;
    //构造函数(类似OC的init方法)。返回结构体对象
  __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;
  }
};
//封装了block执行逻辑的函数
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {

            NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_0a05f8_mi_0);
        }

//block的描述
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)};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
        //定义block变量
//        void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
        //将一些强制转换代码删除
        void (*block)(void) = &__main_block_impl_0(
                                                    __main_block_func_0,
                                                    &__main_block_desc_0_DATA
                                                   );
        //执行block内部的代码
//        ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
        //将一些强制转换代码删除
        block->FuncPtr(block);
    }
    return 0;
}

变量捕获

1.基本数据类型auto变量
auto:自动变量,离开作用域就会销毁

#import 
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int  age = 10;
        void (^block)(void) = ^{
            NSLog(@"Hello World ! %d",age);
        };
        age = 20;
        block();
    }
    return 0;
}

代码运行打印的10,下面我们就来分析一下底层代码:

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  int age;
//age(_age)    C++ 语法,将传进来的_age赋值给结构体的成员变量age
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int _age, int flags=0) : age(_age) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  int age = __cself->age; // bound by copy
            NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_5736dc_mi_0,age);
        }
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        int age = 10;
//定义block时将捕获的age的值传给main_block_impl_0这个函数。
        void (*block)(void) = &__main_block_impl_0(__main_block_func_0, &__main_block_desc_0_DATA, age);
        age = 20;
        block)->FuncPtr(block);
    }
    return 0;
}

2.对象类型的auto变量

#import 
#import "Cat.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //没有捕获auto变量的block是Global
        Cat *cat = [[Cat alloc]init];
        cat.name = @"aaa";
        void (^block)(void) = ^{
            NSLog(@"Hello World ! %@",cat.name);
        };
        block();
        NSLog(@"%@",[block class]);
    }
    return 0;
}

在Cat类中重写dealloc方法,打印Cat的释放时间,运行上面代码发现,Cat类不会被释放。
因为block会捕获Cat类,强引用Cat类且block存放在堆上。

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  Cat *cat;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, Cat *_cat, int flags=0) : cat(_cat) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  Cat *cat = __cself->cat; // bound by copy

            NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_b96010_mi_1,((NSString *(*)(id, SEL))(void *)objc_msgSend)((id)cat, sel_registerName("name")));
        }
//在ARC模式下,系统会自动调用copy方法,_Block_object_assign会根据捕获的auto变量的修饰符(__strong 、__weak)做出强引用或弱引用。 相当于retain
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->cat, (void*)src->cat, 3/*BLOCK_FIELD_IS_OBJECT*/);}

//_Block_object_dispose会释放捕获的auto变量,相当于release
static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->cat, 3/*BLOCK_FIELD_IS_OBJECT*/);}

//当block捕获对象类型的auto变量,block底层的描述函数会多2个函数方法:copy  dispose 
static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 

        Cat *cat = ((Cat *(*)(id, SEL))(void *)objc_msgSend)((id)((Cat *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("Cat"), sel_registerName("alloc")), sel_registerName("init"));
        ((void (*)(id, SEL, NSString * _Nonnull))(void *)objc_msgSend)((id)cat, sel_registerName("setName:"), (NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_b96010_mi_0);
        void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, cat, 570425344));
        ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_b96010_mi_2,((Class (*)(id, SEL))(void *)objc_msgSend)((id)block, sel_registerName("class")));
    }
    return 0;
}

3.static变量

#import 

int main(int argc, const char * argv[]) {
    @autoreleasepool {
       static int  wide = 10;
        void (^block)(void) = ^{
            NSLog(@"Hello World ! %d",wide);
        };
        wide = 20;
        block();
    }
    return 0;
}

打印的值是20

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  int *wide;
//wide(_wide)    C++ 语法,将传进来的__wide赋值给结构体的成员变量*wide
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int *_wide, int flags=0) : wide(_wide) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  int *wide = __cself->wide; // bound by copy

            NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_d13ed3_mi_0,(*wide));
        }

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)};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
       static int wide = 10;
        //定义block时将捕获的wide的地址传给main_block_impl_0这个函数。
        void (*block)(void) = &__main_block_impl_0(__main_block_func_0, &__main_block_desc_0_DATA, &wide);
        wide = 20;
        block)->FuncPtr(block);
    }
    return 0;
}

4.全局变量
block不会捕获全局变量,在block可以直接使用。
self是局部变量,block会捕获self,每个OC方法都有2个隐藏参数,self作为第一个参数

block类型

1.NSGlobalBlock

#import 
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //没有捕获auto变量的block是Global
        static int  age = 10;
        void (^block)(void) = ^{
            NSLog(@"Hello World ! %d",age);
        }; 
        NSLog(@"%@",[block class]);
    }
    return 0;
}
打印为:2021-09-17 16:50:01.955120+0800 Block的本质[60317:3405819] __NSGlobalBlock__

2.NSStackBlock
关闭Xcode的ARC,将Objective-C Automatic Reference Counting 的值设为NO,NSStackBlock存储在栈上,当block出了作用域,NSStackBlock就会被回收,再次调用时会出现数据错乱。

截屏2021-09-17 下午4.57.04.png
#import 
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //捕获auto变量的block是Stack
        int  age = 10;
        void (^block)(void) = ^{
            NSLog(@"Hello World ! %d",age);
        }; 
        NSLog(@"%@",[block class]);
    }
    return 0;
}
打印为:2021-09-17 16:55:35.195563+0800 Block的本质[60355:3408920] __NSStackBlock__

3.NSMallocBlock
当NSStackBlock调用copy方法后,就会变为NSMallocBlock,存储在堆上。
当NSGlobalBlock调用copy方法不会改变block类型,还是存储在数据区。
当NSMallocBlock调用copy方法,block对象的引用计数器会加一。

在ARC环境下,编译器会根据情况自动将栈上的block复制到堆上:
block作为函数返回值时
将block赋值给__strong指针时
block作为Cocoa API中方法名含有usingBlock的方法参数时
block作为GCD API中方法参数时

block修改变量的值

1.将auto局部变量加上static 修饰符 缺点:变量会一直存储在内存中,不会在超出作用域时释放。
2.__block修饰 编译器会将变量包装成一个对象

//系统会将age 包装给一个对象
struct __Block_byref_age_0 {
  void *__isa;
__Block_byref_age_0 *__forwarding;
 int __flags;
 int __size;
 int age;
};

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __Block_byref_age_0 *age; // by ref
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_age_0 *_age, int flags=0) : age(_age->__forwarding) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  __Block_byref_age_0 *age = __cself->age; // bound by ref

            NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_255acd_mi_0,(age->__forwarding->age));
        }
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->age, (void*)src->age, 8/*BLOCK_FIELD_IS_BYREF*/);}

static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->age, 8/*BLOCK_FIELD_IS_BYREF*/);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 



        __attribute__((__blocks__(byref))) __Block_byref_age_0 age = {(void*)0,(__Block_byref_age_0 *)&age, 0, sizeof(__Block_byref_age_0), 10};
        void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_age_0 *)&age, 570425344));
        ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_ym_h2psj2ss52s_y619pxn42rfh0000gn_T_main_255acd_mi_1,((Class (*)(id, SEL))(void *)objc_msgSend)((id)block, sel_registerName("class")));
    }
    return 0;
}

你可能感兴趣的:(Block底层原理)