Block捕获变量

block捕获的变量

  1. 局部变量
  2. 静态局部变量
  3. 全局变量
  4. 静态全局变量
void testBlock() {

    int num = 3;
    NSArray *array;

    static int static_num = 4;
    static NSArray *static_array;

    void(*block)(int) = ((void (*)(int))&__testBlock_block_impl_0((void *)__testBlock_block_func_0, 
                        &__testBlock_block_desc_0_DATA, num, array, &static_num, &static_array, 570425344));
    ((void (*)(__block_impl *, int))((__block_impl *)block)->FuncPtr)((__block_impl *)block, 2);
}
函数执行部分
static void __testBlock_block_func_0(struct __testBlock_block_impl_0 *__cself, int i) {
  int num = __cself->num; // bound by copy
  NSArray *array = __cself->array; // bound by copy
  int *static_num = __cself->static_num; // bound by copy
  NSObject **static_NSObject = __cself->static_NSObject; // bound by copy
  NSLog...
  NSLog...
  NSLog...
总结

局部变量基本数据类型:捕获的值
局部变量对象类型:捕获的是值和属性修饰符
静态局部变量基本数据类型:捕获的是指针
静态局部变量对象类型:捕获的是指针的指针
全局变量:不捕获
静态全局变量:不捕获

应用
void testBlock1() {
    
    int num = 3;
    void(^block)(int) = ^(int i){
        NSLog(@"i * num = %d", num * i);
    };
    num = 4;
    block(2);
    //结果为 6.
    //局部变量基本数据类型捕获的是值,捕获的是值3,3 * 2 = 6;
}
void testBlock1() {
    
    static int num = 3;
    void(^block)(int) = ^(int i){
        NSLog(@"i * num = %d", num * i);
    };
    num = 4;
    block(2);
    //结果为 8.
    //局部变量基本数据类型捕获的是值,捕获的num的指针,num被修改为4,4 * 2 = 8;
}
void testBlock1() {
    
    NSArray *array  = @[@"hello", @"world"];
    void(^block)(int) = ^(int i){
        NSLog(@"array = %@", array);
    };
    array = @[@"1111"];
    block(2); //array = (hello,world)
    //局部变量对象类型,捕获值和属性修饰符。
}
void testBlock1() {
    
    static NSArray *array;
    void(^block)(int) = ^(int i){
        NSLog(@"array = %@", array);
    };
    array = @[@"1111"];
    block(2); //array = (1111)
    //静态局部变量,捕获指针。
}

你可能感兴趣的:(Block捕获变量)