自我阻止 [英] blocks, self, retain cycles
问题描述
我很难在一个块内引用自己,而没有创建保留周期.
I'm having a bit of trouble getting my head around referencing self within a block, and not creating a retain cycle.
您能告诉我我的理解是否正确吗?
Can you let me know if my understanding is correct:
如果我曾经在一个块内引用self,它将创建一个保留周期,而我应该在该块之外创建一个对self的弱引用,然后在该块内使用该弱引用?
If I ever reference self within a block, it will create a retain cycle, and instead I should be creating a weak reference to self outside of the block and then using that weak reference inside the block?
谢谢!
推荐答案
是的,这是正确的,但有一些例外:
Yes, that is correct, with a few exceptions:
仅当self
最终间接保留块时才会发生保留周期,例如在self
myproperty
的属性上设置属性myblock
:
A retain cycle only happens if self
ends up retaining the block indirectly, e.g. setting property myblock
on property of self
myproperty
:
self.myproperty.myblock = ^{ [self dosomething]; }; // ERROR: Retain Cycle
但是,在将块用于调度代码之类的代码时,通常不会发生保留周期:
However, a retain cycle doesn't (usually) happen when using blocks for something like dispatch code, like this:
dispatch_async(dispatch_get_main_queue(), ^{ [self dosomething]; }); // Safe, dispatch_async will not be retained by you
除非您当然要在具有保留周期标准的块内调用dispatch_async
函数.
Unless of course you call that dispatch_async
function inside a block that has the criteria for being a retain cycle.
这确实令人困惑,我希望可以解决此问题.现在,我个人认为:
It is really confusing, and it's something I hope gets fixed. Now, for my own opinion:
情况并非总是如此,在ARC之前的代码中这不是问题,但是由于块现在会自动保留其捕获的所有对象,所以这是一个问题.
It wasn't always the case, in pre-ARC code this wasn't an issue, but since blocks now automatically retain any objects they capture, it's an issue.
我希望通过将self
的类型设置为__weak instancetype const
而不是instancetype const
可以解决此问题,因为这很容易解决.它还可以解决在ARC中创建类集群的一些问题,这虽然不是最大的问题,但仍然存在.
I wish this would get fixed, as it'd be a quite easy fix, by having self
's type be a __weak instancetype const
instead of a instancetype const
. It would also solve some issues with creating class clusters in ARC, which admittedly isn't the largest of issues, but it still exists.
就保留周期而言,优势并不多.
As far as advantages to retain cycles, there are not many.
这篇关于自我阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!