简体   繁体   English

为什么在引用自身时,块会创建一个保留周期?

[英]Why do blocks create a retain cycle when referencing self?

I have read many articles that talk about blocks creating a retain cycle. 我读过许多有关创建保留周期的块的文章。 But why would it make a retain cycle? 但是为什么要进行保留周期呢? Wouldn't the block release the reference after it got run? 块运行后不会释放参考吗?

[UIView animateWithDuration:5
                 animations:^{
            self.variable = somevalue;
}];

For example if the above were executed, the reference to self would be released right? 例如,如果执行上述操作,对self的引用将被释放,对吗?

I already see that the above block creates two strong references. 我已经看到上面的代码块创建了两个强大的参考。 One from the object to the block and the block to the object. 一种是从对象到块,另一种是从块到对象。 Can someone explain to me why the cycle doesn't break? 有人可以向我解释为什么周期不中断吗? Shouldn't the cycle break after the code is run? 代码运行后,循环不应该中断吗?

If an object holds a block and the block holds the object then that's a cycle. 如果一个对象包含一个块,而该块包含该对象,则为一个循环。

If someone else holds the block and the block holds the object then there's a cycle only if the object directly or indirectly holds whomever holds the block. 如果其他人持有该块并且该块持有该对象,则只有对象直接或间接持有该块的所有人时,才会有一个循环。

Blocks do not self destruct upon being run so the cycle will be broken only if the block is deallocated. 块在运行时不会自毁,因此仅当释放了块时才会中断循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM