Pablo
Pablo

Reputation: 29519

deinit not called on boilerplate macOS app

I've created new app from macOS Cocoa App template. The only change I've made is added deinit in NSViewController. So now it looks like this(complete code):

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    func doSomething()
    {
        var a = 10
        a = a + 1
        print(a)
    }

    deinit {
        doSomething()
        print("deinit called")
    }
}

Why I don't see deinit call? I've searched number of questions here, but couldn't find answer, as I don't have any retain cycle.

Upvotes: 3

Views: 418

Answers (2)

Duncan C
Duncan C

Reputation: 131408

As Tobi says in his answer, deinit gets called right before an object is deallocated.

An object gets deallocated when there are no longer any strong references to it. (Nobody owns the object any more.)

In order to answer your specific question you need to look at how your view controller is created an who owns it.

I haven't done much Mac development in a while, so I'm kinda rusty on view controller lifecycle, but here's my recollection of how it works:

If you only have one app window, it is the view controller's owner, and the window never gets closed, that means the view controller will never get deallocated.

If you quit the app I don't think the system tears down your window hierarchy before terminating the app (unless you're app is a document-based app, in which case the app will be told to close all of it's document windows before quitting.)

Upvotes: 1

Mohmmad S
Mohmmad S

Reputation: 5088

A deinitializer is called immediately before a class instance is deallocated.

Altho your question is not clear to me.

But the usual reason for failure to trigger deinit when expected is that you have a retain cycle that prevents your view controller from going out of existence.

Sometimes the reason is that your expectation that the view controller would be destroyed under the circumstances is incorrect.

But assuming it is correct, a retain cycle is the reason.

another suggestion is to use Hierarchies Debug.

answer those questions for your self.

is this the root UIViewController ?

is it dismissed properly ?

Upvotes: 0

Related Questions