Search code examples
iosmemory-managementretainautomatic-ref-counting

iOS - a custom class having reference to UIViewController object


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


Solution

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