Manuel Manuel - 6 months ago 14
Swift Question

Why does NSObject get deallocated while it presents its UIViewController?


presents a view controller:

class myObject: NSObject {

var myVC = UIViewController()

func present() {
let rootVC = UIApplication.sharedApplication().keyWindow!.rootViewController
rootVC.presentViewController(myVC, animated: animated, completion: nil)

Why does
get deallocated (deinit is called) when
is presented and still visible on the screen? Shouldn't it stay allocated because
is its property?

Update: The effective problem I face is that
shows a view with controls whose delegate is
. Because
is deallocated the controls cannot call the delegate anymore because I reference the delegate as
. However when I have a strong reference to the delegate
stays allocated and the delegate gets called. But it smells fishy to use a strong reference for the delegate.


The ARC memory management is based on ownership. Once an object is not owned by any other object, it gets deallocated. There is always a root object which owns all others - the UIApplication. The ownership of all objects in the application can be described with a tree:

  - UIApplicationDelegate
       - rootViewController
            - child controllers
               - child controllers ...
       - window
            - subviews
               - subviews ...
       - ... other objects

You can create other root objects (other ownership trees), of course, e.g. by using singletons.

If you instance is not owned by an object in this hierarchy tree, it gets deallocated. Therefore you should build your ownership hierarchy in a way that controllers are owned only by other controllers, not by custom objects.

If you need a reference to the owner, that's usually the time to use a weak reference, to avoid cyclical ownerships.

Also note that UIViewController takes some significant memory on the heap so it is not very common to keep references to them once they are not needed. It's more common to create new instances before presenting them (although exceptions exist).