Igor Cova Igor Cova - 3 months ago 27
Swift Question

Crash application on dismiss ViewController OS X (Swift)

It should be a decision on OS X Swift

Problem - application crashed on represent NSViewController

There have two NSViewController – the problem, when I do a transition between them - application closed with error on represent NSViewControllers.
There use the methods of presentViewController and dismissViewController.

Example project with problem here: git@github.com:IgorCova/Freelance.git

How to reproduce the error (on Yosemite only):
1. I open first NSViewController
2. After I open second NSViewController
3. Next, go back to the first (dismiss second)
4. Then again trying to open a second NSViewController - in the end, the application crushes (But on El Capitan everything works without errors)

Answer

In your SecondViewController’s viewDidLoad() you register itself as an observer for "dismisSecondViewController" notification:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SecondViewController.dismisSelf),
                                                           name:"dismisSecondViewController",
                                                         object: nil)

The problem is that prior to 10.11 you have to unregister any observers before they get deallocated (i.e. removed from memory), otherwise NSNotificationCenter will continue to send messages to something that now occupies this deallocated memory region — it may be either garbage or some other object that doesn't respond to these messages. Since your view controllers clearly get deallocated when you switch them, this is your issue.

So the fix is easy: add the following deinit method to your SecondViewController class

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}