Objective - C block(二)block的类型及捕获变量

(一)block 捕获变量类型

为了保证block内部能够正确访问外部的变量,block有一个变量捕获机制


不同的变量类型捕获
(1)变量捕获为auto
int main(int argc, const char * argv[]) {
    @autoreleasepool {
      int age = 10;//auto 变量
      void(^block2)(int,int) = ^(int a,int b){
        NSLog(@"this is a block == %d" , age);
      };
      block2(20,30);
    }  
  return 0;
}

转为C++代码(只截取重要部分):

//block底层结构
struct __main_block_impl_1 {
  struct __block_impl impl;
  struct __main_block_desc_1* Desc;
  int age;  //捕获age的值
  __main_block_impl_1(void *fp, struct __main_block_desc_1 *desc, int _age, int flags=0) : age(_age) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __main_block_func_1(struct __main_block_impl_1 *__cself, int a, int b) {
    int age = __cself->age; // bound by copy
    NSLog((NSString *)&__NSConstantStringImpl__var_folders_f9__q8q2xr131vf4h1cy7837sm00000gn_T_main_142399_mi_1 , age);
  }
(2)变量捕获为static
int main(int argc, const char * argv[]) {
    @autoreleasepool {
      static int age = 10;//static 局部变量
      void(^block2)(int,int) = ^(int a,int b){
        NSLog(@"this is a block == %d" , age);
      };
      block2(20,30);
  }
  return 0;
}

转为C++代码(只截取重要部分):

struct __main_block_impl_1 {
  struct __block_impl impl;
  struct __main_block_desc_1* Desc;
  int *age;  //捕获age的地址
  __main_block_impl_1(void *fp, struct __main_block_desc_1 *desc, int *_age, int flags=0) : age(_age) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_1(struct __main_block_impl_1 *__cself, int a, int b) {
  int *age = __cself->age; // bound by copy

            NSLog((NSString *)&__NSConstantStringImpl__var_folders_f9__q8q2xr131vf4h1cy7837sm00000gn_T_main_b17032_mi_1 , (*age));
        }
(3)变量捕获为static
int age = 10;//全局变量
static int height = 10;//静态全局变量

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        void(^block)(void) = ^{
            NSLog(@"hello,world!");
        };
        block();
        

        void(^block2)(int,int) = ^(int a,int b){
            NSLog(@"this is a block a == %d height == %d" , age, height);
        };
        block2(20,30);
    }
    return 0;
}

转为C++代码(只截取重要部分):

int age = 10;
static int height = 10;

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;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {

            NSLog((NSString *)&__NSConstantStringImpl__var_folders_f9__q8q2xr131vf4h1cy7837sm00000gn_T_main_3a42c5_mi_0);
        }

通过上面的3种不同变量进行block内部访问的时候:(从正确的访问值的角度来看)

  1. auto变量会随着函数的生命周期结束,为了保证正确访问,所以会捕获其值
  2. static局部变量,会长期保存,但是无法直接访问,所以需要捕获变量的地址
  3. 全局变量可以直接访问,所以不需要捕获
疑问(1):如果是对象方法内部调用block,block内部访问self,会捕获吗?
此时self会被捕获吗?
struct __ZQPerson__test_block_impl_0 {
  struct __block_impl impl;
  struct __ZQPerson__test_block_desc_0* Desc;
  ZQPerson *self;//self被捕获
  __ZQPerson__test_block_impl_0(void *fp, struct __ZQPerson__test_block_desc_0 *desc, ZQPerson *_self, int flags=0) : self(_self) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __ZQPerson__test_block_func_0(struct __ZQPerson__test_block_impl_0 *__cself) {
  ZQPerson *self = __cself->self; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_f9__q8q2xr131vf4h1cy7837sm00000gn_T_ZQPerson_b92927_mi_0,self);
    }
疑问(2):如果是对象方法内部调用block,block内部访问成员变量,会捕获什么呢?
捕获self
static void __ZQPerson__test_block_func_0(struct __ZQPerson__test_block_impl_0 *__cself) {
  ZQPerson *self = __cself->self; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_f9__q8q2xr131vf4h1cy7837sm00000gn_T_ZQPerson_2c7733_mi_0,(*(NSInteger *)((char *)self + OBJC_IVAR_$_ZQPerson$_age)));
    }//从self的IVAR列表中找到对应的成员变量
疑问(2):如果是对象方法内部调用block,block内部使用点语法,会捕获什么呢?
捕获self
static void __ZQPerson__test_block_func_0(struct __ZQPerson__test_block_impl_0 *__cself) {
  ZQPerson *self = __cself->self; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_f9__q8q2xr131vf4h1cy7837sm00000gn_T_ZQPerson_1c2f87_mi_0,((NSInteger (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("age")));//给捕获的self发送一条消息 调用age方法
    }

OC对象所有的方法,其实内部传递了两个参数,self和_cmd(方法调用者和方法名),所以这里捕获的self就是局部变量


ZQPerson的setAge和age方法底层传参

(二)block 类型

我们在上一章可以知道block是一个OC对象,继承自NSObject

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        void(^block1)(void) = ^{
            NSLog(@"hello,world");
        };
        block1();
        
        int age = 10;
        void(^block2)(int,int) = ^(int a,int b){
            NSLog(@"this is a block a == %d" , age);
        };
        block2(20,30);
        
        NSLog(@"%@ %@ %@",[block1 class],[block2 class],[^{
            NSLog(@"%d",age);
        } class]);
        
    }
    return 0;
}

输出结果:

__NSGlobalBlock__ __NSMallocBlock__ __NSStackBlock__

可以知道block一共有3种类型:__NSGlobalBlock____NSMallocBlock____NSStackBlock__,但是我们在转化为C++代码后发现,3中block的impl.isa均为_NSConcreteStackBlock,是为什么呢?

底层均为_NSConcreteStackBlock

(1)block的3种类型

block有3种类型,可以通过调用class方法或者isa指针查看具体类型,最终都是继承自NSBlock类型

  • NSGlobalBlock ( _NSConcreteGlobalBlock )
  • NSStackBlock ( _NSConcreteStackBlock )
  • NSMallocBlock ( _NSConcreteMallocBlock )
    三种block内存存储区域

    那么三种block是如何定义的呢?
    image.png

没有访问auto变量的NSGlobalBlock实际使用场景意义不大,所以不再深入研究。我们首先需要关闭ARC,因为ARC实际为开发者做了很多事情,无法研究其本质

ARC -> MRC (Build Setting -> automatic reference Counting 设置为NO)

当前环境为MRC的情况下,上面的代码输出结果为:

__NSGlobalBlock__   __NSStackBlock__   __NSStackBlock__

因此,由此可见,访问了auto变量的block即为NSStackBlock

NSStackBlock存在什么问题呢?或者说在ARC环境下,为什么有些stackBlock会变成mallocBlock呢?

void (^block2)(void);

void test(){
    int age = 10;
    block2 = ^{
        NSLog(@"age is %d",age);//输出结果:age is -272632600
    };
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        
        
        int age = 10;
        void(^block1)(int,int) = ^(int a,int b){
            NSLog(@"this is a block a == %d" , age);
        };
        block1(20,30);
        
        test();
        block2();
    }
    return 0;
}

在上面的代码(MRC环境下),block2随着函数调用完毕,block2的内存即被释放,因此访问age即为垃圾数据。因此我们将block2进行copy操作,block2就成为NSMallocBlock

void (^block2)(void);

void test(){
    int age = 10;
    block2 = [^{
        NSLog(@"age is %d",age);//输出结果:age is 10
    } copy];
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        
        
        int age = 10;
        void(^block1)(int,int) = ^(int a,int b){
            NSLog(@"this is a block a == %d" , age);
        };
        block1(20,30);
        
        test();
        block2();
    }
    return 0;
}
疑问(1)如果对globalBlock、mallocBlock进行copy操作,又会是什么效果呢?
不同的block进行copy的效果

ARC环境下,系统会根据自动将部分stackblock进行copy操作

你可能感兴趣的:(Objective - C block(二)block的类型及捕获变量)