ios - 中断嵌套在另一个块中的块中的保留循环
问题描述
有时我使用嵌套在另一个块中的块,这是我的代码
- (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 {
}
解决方案
我认为您可以在嵌套块中创建新的强引用,如下所示:
- (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
嵌套块范围中的第一个。并且它只会在嵌套块的执行期间处于活动状态,而不会创建强引用循环。我想是的 =)
推荐阅读
- svelte - 子目录的 Sveltekit 基本 URL 抛出 404
- javascript - Javascript UDF 中 BigQuery 中的 UTF 规范化问题
- c# - 在不暂停程序的情况下读取正在按下的特定键
- javascript - Javascript 字典键未在 axios 请求中更新
- c# - 复制和应用旋转值的问题
- reactjs - 如何使用通过节点后端发送的 React 下载不同类型的文件类型?
- video - FFMPEG- 无法为输出文件 #0 写入标头(编解码器参数不正确?):不允许操作 初始化输出流时出错 0:2 --
- flutter - 现有集团的 BlocProvider.value 或 BlocListener.bloc?
- python - Python 3:比较两个数字并返回 -1、0 或 1
- javascript - `tsconfig` 中的“路径”没有从 node_modules 中获取声明,模块导入指向父目录