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

发布于 2024-12-11 16:45:44 字数 410 浏览 0 评论 0原文

首先,我使用 ARC 并针对 iOS4+,

我有一个自定义类,需要引用自定义 UIViewController。 除非我误解了什么,否则在该引用上拥有属性 retain 意味着每当我的类解构时, UIViewController 也会解构吗? 或者这是否意味着appdelegate(创建了UIViewController)和我的自定义类都需要被释放才能释放UIViewController?

所以我还阅读了有关 __unsafe_unretained 属性的内容。我的自定义类可以简单地使用它而不复杂地引用 UIViewController 吗?由于appdelegate最终会释放UIViewController,所以不存在悬空指针的风险吗?

谢谢

编辑:自定义类是一个单例对象,如果重要的话它将贯穿整个过程

First of, I am using ARC and targeting iOS4+

I have a custom class that needs a reference to a custom UIViewController.
Unless I have missunderstod something, having the property retain on that reference means that whenever my class destructs, the UIViewController destructs aswell?
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?

So I also read about __unsafe_unretained property. Can my custom class simply use that without complications to reference the UIViewController? Since the appdelegate would deallocate the UIViewController in the end anyway, there is no risk of a dangling pointer?

Thanks

EDIT: The custom class is a singleton object that will live through the entire process if it matters

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滥情哥ㄟ 2024-12-18 16:45:44

每个对象都有一个保留计数,本质上决定了它是否需要保留。在这种情况下,您的 AppDelegate 已经保留了 UIViewController(保留计数为 1),但这并不意味着您的自定义类也不能保留 UIViewController(保留计数为 2)。所以你的第二种情况更接近事实:当你的自定义类破坏并释放 UIViewController 时,保留计数将回落到 1。然后,当 AppDelegate 破坏并释放它时,计数将下降到 0 并且对象将被销毁。

更进一步,如果在自定义类中将 UIViewController 分配给另一个也保留它的内置或自定义类,则计数将继续增加,然后随着每个对象依次释放其值而下降。兴趣。

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). 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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文