0

I'm curious about the chain of object ownership in UIKit, going up from a UIViewController. Using the memory debugger in Xcode, I see that the UIViewController is owned (via a strong reference) by the UIWindow. The only strong reference to that UIWindow is from the app's UIApplicationDelegate.

The UIApplicationDelegate doesn't seem to have any inbound strong references (the UIApplication has a weak reference). What object actually owns the delegate and prevents it from being deallocated?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Cal Stephens
  • 725
  • 9
  • 20
  • From the [documentation](https://developer.apple.com/documentation/uikit/uiapplicationdelegate): `the app delegate is a singleton object and is always present at runtime`. – JAL Aug 17 '17 at 18:35
  • 1
    Related: [Where are static variables stored (in C/C++)?](https://stackoverflow.com/q/93039/2415822) – JAL Aug 17 '17 at 18:35
  • @JAL: The application delegate is not a static variable. If you override `init` in AppDelegate and set a breakpoint then one can see that alloc/init is called on the application delegate in a _UIApplicationMainPreparations function. It *seems* that an associated reference is set to keep it alive. Unfortunately, the UIKit runtime is not open source, so it is difficult to tell how exactly it works. – Martin R Aug 17 '17 at 19:27
  • @MartinR Interesting, did not know that. So does that mean the documentation is "technically" incorrect, since an internal UIApplication object is holding a reference to it somewhere and it's not a "true" singleton? – JAL Aug 17 '17 at 19:29
  • 1
    Most "singletons" are actually "shared instances". You (or I or Cal) define the AppDelegate class, and it is no problem to create another instance with `let ad = AppDelegate()`. The documentation probably means: Some instance is created at startup and assigned to `UIApplication.delegate`. – Martin R Aug 17 '17 at 19:34

0 Answers0