我阅读了以下 article但我对以下段落有点困惑。
Apple documentation says that “For non-trivial cycles, however, you should use” this approach:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyController = myController;
myController.completionHandler = ^(NSInteger result) {
MyViewController *strongMyController = weakMyController;
if (strongMyController) {
// ...
[strongMyController dismissViewControllerAnimated:YES completion:nil];
// ...
}
else {
// Probably nothing...
}
};
First of all, this example looks wrong to me. How can self be deallocated and be nilled out if the block itself is retained in the completionHandler property? The completionHandler property can be declared as assign or unsafe_unretained to allow the object to be deallocated after the block is passed around. I can’t see the reason for doing that. If other objects need the object (self), the block that is passed around should retain the object and therefore the block should not be assigned to a property. No _weak/_strong usage should be involved in this case.
他说“如果其他对象需要对象(self):” 他这里的需要是什么意思?是这样的吗:他们需要 self ,因为他们访问需要 self 的 block (传递给他们的 block ),所以他们需要 self 。如果不是他是什么意思?
然后他说“因此不应将 block 分配给属性。” 但是,如果有多个对象需要在未来某个未定义的时间阻塞怎么办?因此,我们可以通过从该属性中获取来将 block 传递给他们。
我是不是理解错了?
最佳答案
这篇文章的作者有点糊涂,把一些东西弄反了。
How can self be deallocated and be nilled out if the block itself is retained in the completionHandler property?
如果 block 保留在 completionHandler
中,则意味着 self
对该 block 具有强引用,这意味着只要 self
是——而不是相反。 self
保留 block 与 self
是否被释放无关。
The completionHandler property can be declared as assign or unsafe_unretained to allow the object to be deallocated after the block is passed around.
同样,completionHandler
是强引用还是弱引用会影响 block 的生命周期。它与self
的生命周期指向的对象无关。
If other objects need the object (self), the block that is passed around should retain the object and therefore the block should not be assigned to a property.
没有。该对象保留该 block 。该 block 不保留对象。
在大多数情况下是否需要代码示例中显示的模式是值得商榷的。然而,作者的推理是错误的。
关于ios - 非平凡循环中的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20619183/