iOS高级进阶

__block修饰符窥探

2019-10-09  本文已影响0人  南城同學
场景:
       int age = 10; 
        Block block1 = ^{
            age = 20;
        };
不可以在block内部直接修改age的原因:
//1
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  int 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;
  }
};
//2
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
                         
       int age = __cself->age;
}

//3
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
        
        int age = 10;
        Block block = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, age);
        ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
    }
    return 0;
}

__block的本质
 __block int age = 10;
struct __Block_byref_age_0 {
  void *__isa; //0
__Block_byref_age_0 *__forwarding; //&age:指向自身的指针
 int __flags;//0
 int __size;//sizeof(__Block_byref_age_0)
 int age; //10
};
应用:

思考1:
NSMutableArray *arr = [NSMutableArray array];
Block block = ^{
       [arr addObject:@"123"];
};
block;

需要加__block吗?


思考2:
上一篇 下一篇

猜你喜欢

热点阅读