简体   繁体   English

解雇视图控制器时为什么不保留圆圈(非圆弧)

[英]Why not circle retain when dismiss view controller (non-arc)

I have this code in non-arc, and I think it has a problem - circle retain ( self (UIViewController) has the ownership of complete-block, complete-block has the ownership of self ). 我有非弧的代码,我认为它有一个问题 - 圈保留( self(UIViewController)拥有完整块的所有权,完全块拥有自己的所有权 )。 But when I debug, it run in dealloc (mean that not have circle retain count as I think) 但是当我调试时,它在dealloc中运行(意味着我认为没有圆圈保留计数)

[self dismissViewControllerAnimated:YES completion:^{
    [self goToChatViewController:buddyEntity];
}];

Can someone explain for me, why it not circle retain in this code? 有人可以为我解释一下,为什么它不会圈在这段代码中?

You don't hold reference at this block. 你没有在这个街区举行参考。 So this block deallocated after completion. 所以这个块在完成后解除分配。 When block deallocating it release object that it hold. 当块解除分配时,它释放它所持有的对象。 So there is all ok. 所以没关系。 You can courageously use self inside such blocks. 你可以勇敢地在这些街区内使用self

Retain cycles appear for example if you use block as property or add it in container. 例如,如果使用块作为属性或将其添加到容器中,则会出现保留周期。

A block is secretly an ObjectiveC object. 一个块秘密地是一个ObjectiveC对象。 When you create a block in the background objectiveC creates an instance of a block class (although quite weirdly it creates it on the stack rather than the heap, unless you copy the block). 当你在后台创建一个块时,ObjectiveC会创建一个块类的实例(尽管非常奇怪,它会在堆栈而不是堆上创建它,除非你复制块)。 The objects used inside of your block become instance variables of the block object. 块内使用的对象成为块对象的实例变量。

Because the block object is on the heap, not on the stack normally when you get to the end of the method you are in the block object falls out of scope and everything is great. 因为块对象在堆上,而不是在堆栈上,所以当你到达方法的末尾时,你在块对象中的范围超出范围,一切都很好。 However if your class calls copy on the block, and keeps a reference, the block is copied to the heap. 但是,如果您的类在块上调用copy并保留引用,则该块将被复制到堆中。 Now your class has a reference to the block and the block has a reference to your class and you have a retain cycle. 现在你的类有一个块的引用,块有一个对你的类的引用,你有一个保留周期。

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

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