gpt4 book ai didi

ios - 使用操作队列保留周期

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:49 26 4
gpt4 key购买 nike

在阅读 blog about concurrency 时在 iOS 中,我偶然发现了下一段代码:

__weak id weakSelf = self;
[self.operationQueue addOperationWithBlock:^{
NSNumber* result = findLargestMersennePrime();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
MyClass* strongSelf = weakSelf;
strongSelf.textLabel.text = [result stringValue];
}];
}];

作者解释说需要使用 weakref 是因为:

we need to make a weak reference to self, otherwise we create a retain cycle (the block retains self, the private operation queue retains the block, and self retains the operation queue). Within the block we convert it back to a strong reference to make sure it doesn’t get deallocated while running the block.

我能理解为什么该 block 会保留 self,但我不明白私有(private)操作队列为何(以及确切位置)保留该 block 以及 self 何时/何地保留操作队列。任何解释将不胜感激。

最佳答案

尝试在没有弱引用的情况下编写这段代码:

[self.operationQueue addOperationWithBlock:^{
NSNumber* result = findLargestMersennePrime();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.textLabel.text = [result stringValue];
}];
}];

使此代码工作 - 编译器在 operationQueue 中保留对 self 的引用,以避免 self 从内存中删除并且 self.textLabel.text = .. 被执行,所以它试图保证对象是活的。

这是实际创建循环的地方:

  1. self保留operationQueue(这意味着当self活着的时候operationQueue不能被删除)
  2. operationQueue 保留 self(这意味着当 operationQueue 处于事件状态时不能删除 self)

为避免这种情况 - 您正在创建周引用,因此您正在消除第二次保留

附言。 “ block ”是 operationQueue 的一部分,因此我们可以假设此方案中只有 2 个项目。

关于ios - 使用操作队列保留周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23149084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com