首页 > 解决方案 > 中断嵌套在另一个块中的块中的保留循环

问题描述

有时我使用嵌套在另一个块中的块,这是我的代码

- (void)test {
    __weak typeof(self) weakSelf = self;
    [self.viewSource fetchData:^(BOOL succeed, NSError * _Nonnull error, id  _Nonnull data) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.dataSource disposalData:^{
        // here is the strongSelf ok? do I have to do something to avoid retain cycle?
            [strongSelf updateUI];
        }];
    }];
}
- (void)updateUI {
    
}

我怀疑内部块仍然有保留周期?

    [strongSelf.dataSource disposalData:^{
        [strongSelf updateUI];
    }];

我的问题是在这种情况下打破保留周期的正确方法是什么?


这是额外的讨论,正如许多朋友提到的那样,如果我删除__strong typeof(weakSelf) strongSelf = weakSelf;,内部块没有保留循环?它完全正确吗?

- (void)test {
    __weak typeof(self) weakSelf = self;
    [self.viewSource fetchData:^(BOOL succeed, NSError * _Nonnull error, id  _Nonnull data) {
        [weakSelf.dataSource disposalData:^{
            [weakSelf updateUI];
        }];
    }];
}
- (void)updateUI {
    
} 

标签: iosobjective-cblockretain-cycle

解决方案


我认为您可以在嵌套块中创建新的强引用,如下所示:

- (void)test {
    __weak typeof(self) weakSelf = self;
    [self.viewSource fetchData:^(BOOL succeed, NSError * _Nonnull error, id  _Nonnull data) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.dataSource disposalData:^{
            __strong typeof(weakSelf) strongSelf = weakSelf; // <- new strong ref
            [strongSelf updateUI];
        }];
    }];
}

它将覆盖strongSelf嵌套块范围中的第一个。并且它只会在嵌套块的执行期间处于活动状态,而不会创建强引用循环。我想是的 =)


推荐阅读