简体   繁体   English

iOS-引用UIViewController对象的自定义类

[英]iOS - a custom class having reference to UIViewController object

First of, I am using ARC and targeting iOS4+ 首先,我正在使用ARC,并定位到iOS4 +

I have a custom class that needs a reference to a custom UIViewController. 我有一个自定义类,需要对自定义UIViewController的引用。 Unless I have missunderstod something, having the property retain on that reference means that whenever my class destructs, the UIViewController destructs aswell? 除非我有误解,否则retain该引用的属性意味着每当我的类销毁时,UIViewController也会销毁? Or does it mean that both the appdelegate (which created the UIViewController) and my custom class needs to be deallocated in order for the UIViewController to be deallocated? 还是这意味着需要重新分配appdelegate(创建UIViewController)和我的自定义类,才能重新分配UIViewController?

So I also read about __unsafe_unretained property. 因此,我还阅读了有关__unsafe_unretained属性的信息。 Can my custom class simply use that without complications to reference the UIViewController? 我的自定义类可以简单地使用它而不会复杂地引用UIViewController吗? Since the appdelegate would deallocate the UIViewController in the end anyway, there is no risk of a dangling pointer? 由于appdelegate最终还是会取消分配UIViewController,因此没有悬空指针的风险吗?

Thanks 谢谢

EDIT: The custom class is a singleton object that will live through the entire process if it matters 编辑:自定义类是一个单例对象,如果有问题,它将贯穿整个过程

Each object has a retain count that essentially determines whether or not it needs to stick around. 每个对象都有一个保留计数,该保留计数从本质上确定是否需要保留。 In this case your AppDelegate has retained the UIViewController already (retain count of 1), but that does not mean that your custom class cannot also retain the UIViewController (retain count of 2). 在这种情况下,您的AppDelegate已经保留了UIViewController(保留计数为1),但这并不意味着您的自定义类也不能保留UIViewController(保留计数为2)。 So your second scenario is closer to the truth: when your custom class destructs and releases the UIViewController the retain count will drop back to 1. Then, when the AppDelegate destructs and releases it the count will drop to 0 and the object will be destroyed. 因此,第二种情况更接近于事实:自定义类破坏并释放UIViewController时,保留计数将回落到1。然后,当AppDelegate破坏并释放它时,计数将下降为0,并且对象将被销毁。

To take this a step further, if inside of your custom class you assigned the UIViewController to another bult-in or custom class which also retained it the count would keep going up and then it would drop back as each of those objects in turn released its interest. 更进一步,如果在您的自定义类中将UIViewController分配给另一个保留或保留的自定义类,则计数将继续增加,然后随着每个对象依次释放其计数而回落利益。

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

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