Block(2)

验证时需要关闭ARC

block的三种类型

__NSGlobalBlock__
__NSStackBlock__
__NSMallocBlock__

以上三种类型的block,代表着block在内存中的不同的存放区域。

  • __NSGlobalBlock__存放在数据区(系统管理内存)。
  • __NSStackBlock__ 存放在栈区(系统管理内存)。
  • __NSMallocBlock__ 存放在堆区(开发者管理内存)。

NSGlobalBlock

结论:未捕获auto变量时,类型为__NSGlobalBlock__

验证方式,如下:

无auto变量

int main(int argc, const char * argv[]) {
    void(^block)(void) = ^{
        NSLog(@"a");
    };
    NSLog(@"%@",[block class]);
    return 0;
}

static变量

int main(int argc, const char * argv[]) {
    static int a = 1;
    void(^block)(void) = ^{
        NSLog(@"a=%d",a);
    };
    NSLog(@"%@",[block class]);
    return 0;
}

NSStackBlock

结论:捕获auto变量时,类型为__NSStackBlock__

auto变量

int main(int argc, const char * argv[]) {
    int a = 1;
    void(^block)(void) = ^{
        NSLog(@"a=%d",a);
    };
    NSLog(@"%@",[block class]);
    return 0;
}

NSMallocBlock

结论:当对__NSStackBlock__发送copy消息时,block的类型就变为__NSMallocBlock__

  • __NSStackBlock__类型的block发送copy
int main(int argc, const char * argv[]) {
    int a = 1;
    void(^block)(void) = ^{
        NSLog(@"a=%d",a);
    };
    NSLog(@"%@",[[block copy] class]);
    return 0;
}

结果: 2018-08-21 10:39:36.832469+0800 BlockTest[2682:156539] __NSMallocBlock__

  • __NSGlobalBlock__类型的block发送copy
int main(int argc, const char * argv[]) {
    void(^block)(void) = ^{
        NSLog(@"a=");
    };
    NSLog(@"%@",[[block copy] class]);
    return 0;
}

结果: 2018-08-21 10:42:50.317564+0800 BlockTest[2746:160982] __NSGlobalBlock__

  • __NSMallocBlock__类型的block发送copy
int main(int argc, const char * argv[]) {
    int a = 1;
    void(^block)(void) = ^{
        NSLog(@"a=%d",a);
    };
    NSLog(@"%@",[[[block copy] copy] class]);
    return 0;
}

结果: 2018-08-21 10:43:49.254366+0800 BlockTest[2818:162848] __NSMallocBlock__

ARC环境

ARC环境下不同的是捕获auto变量时,block类型为__NSMallocBlock__

int main(int argc, const char * argv[]) {
    auto int a = 1;
    void(^block)(void) = ^{
        NSLog(@"a=%d",a);
    };
    NSLog(@"%@",[block class]);
    return 0;
}

结果: 2018-08-22 16:37:12.497210+0800 BlockTest[50431:1143805] __NSMallocBlock__

You Might Also Like
发表评论