iOS block嵌套block中weakify的使用

结论:嵌套中的block只需要写strongify,不需要再写一次weakify

只要持有block的变量和block中的变量不是同一个变量(可以指向同一个变量),就不会因此循环引用,导致memory leak。

下面对比两段代码:

 @weakify(self)
    self.blockA = ^{
        @strongify(self)
        [self doSomething];
        //不加weakify
        self.blockB = ^{
            @strongify(self)
            [self doSomething];
        };
    };
复制代码
 @weakify(self)
    self.blockA = ^{
        @strongify(self)
        [self doSomething];
        //加weakify
        @weakify(self)
        self.blockB = ^{
            @strongify(self)
            [self doSomething];
        };
    };
复制代码

预编译之后:

不加weakify

  @autoreleasepool {} 
    __attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);
    self.blockA = ^{
        @autoreleasepool {}
         __attribute__((objc_ownership(strong))) __typeof__(self) self = self_weak_;
       [self doSomething];
        self.blockB = ^{
            @autoreleasepool {}
           __attribute__((objc_ownership(strong))) __typeof__(self) self = self_weak_;
           [self doSomething];
        };
    };
复制代码

加weakify

@autoreleasepool {} 
     __attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);
    self.blockA = ^{
        @autoreleasepool {}
        [self doSomething];
        @autoreleasepool {} __attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);
        self.blockB = ^{
            @autoreleasepool {}
             __attribute__((objc_ownership(strong))) __typeof__(self) self = self_weak_;
             [self doSomething];
        };
    };
复制代码

通过对比可以发现,第二层嵌套外增加的weakify(self)编译之后为__attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);,和第一层嵌套外加的weakify(self)编译之后的代码一样,做了相同的工作,无非就是重新定义了一个没有发生变化的self_weak_变量。

所以,当block嵌套block的时候,内部的block不需要再次增加@weakify(self)。

转载于:https://juejin.im/post/5b9b24b05188255c372f437c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值