iOS block底层原理

block 使用示例

#import <Foundation/Foundation.h>

void blockFunc1 (){
    int num1 = 100;
    void (^block1)(void) = ^{
        NSLog(@"num1 : %d", num1);
    };
    num1 = 200;
    block1();
}

void blockFunc2 (){
    __block int num2 = 300;
    void (^block2)(void) = ^{
        NSLog(@"num2 : %d", num2);
    };
    num2 = 400;
    block2();
}

int num3 = 500;
void blockFunc3 (){
    void (^block3)(void) = ^{
        NSLog(@"num3 : %d", num3);
    };
    num3 = 600;
    block3();
}

void blockFunc4 (){
   static int num4 = 700;
    void (^block4)(void) = ^{
        NSLog(@"num4 : %d", num4);
    };
    num4 = 800;
    block4();
}

static int num5 = 900;
void blockFunc5 (){
    void (^block5)(void) = ^{
        NSLog(@"num5 : %d", num5);
    };
    num5 = 1000;
    block5();
}

void blockFunc6 (int num6){
    void (^block6)(void) = ^{
        NSLog(@"num6 : %d", num6);
    };
    num6 = 1200;
    block6();
}


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        blockFunc1();
        blockFunc2();
        blockFunc3();
        blockFunc4();
        blockFunc5();
        blockFunc6(900);
    }
    return 0;
}

clang _rewrite_objc xx.m 查看转换成 c 的结果

1.使用局部变量(即自动变量)
// 函数
static void __blockFunc1_block_func_0(struct __blockFunc1_block_impl_0 *__cself) {

  // 拷贝进去了 在与原来无关
  int num1 = __cself->num1; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_0w_gpv44s255wb947z91wgbtrww0000gn_T_main_2147bd_mi_0, num1);
}
2.使用__block
static void __blockFunc2_block_func_0(struct __blockFunc2_block_impl_0 *__cself) {

  // 引用?
  __Block_byref_num2_0 *num2 = __cself->num2; // bound by ref

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_0w_gpv44s255wb947z91wgbtrww0000gn_T_main_2147bd_mi_1, (num2->__forwarding->num2));
    }
3.使用全局变量
static void __blockFunc3_block_func_0(struct __blockFunc3_block_impl_0 *__cself) {

//  没有拷贝
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_0w_gpv44s255wb947z91wgbtrww0000gn_T_main_2147bd_mi_2, num3);
    }
4.使用局部静态变量
static void __blockFunc4_block_func_0(struct __blockFunc4_block_impl_0 *__cself) {
  int *num4 = __cself->num4; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_0w_gpv44s255wb947z91wgbtrww0000gn_T_main_2147bd_mi_3, (*num4));
    }
5.使用全局静态变量
static void __blockFunc5_block_func_0(struct __blockFunc5_block_impl_0 *__cself) {
        // 没有做 拷贝的操作
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_0w_gpv44s255wb947z91wgbtrww0000gn_T_main_2147bd_mi_4, num5);
    }
6.使用参数
static void __blockFunc6_block_func_0(struct __blockFunc6_block_impl_0 *__cself) {
  //  也是拷贝了
  int num6 = __cself->num6; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_0w_gpv44s255wb947z91wgbtrww0000gn_T_main_2147bd_mi_5, num6);
    }

推荐阅读更多精彩内容