0

I have a NSViewController that has a class variable as follows:

class ServerAdminViewController: NSViewController, NSTextFieldDelegate, MyTableViewDelegate {

    var myClass = MyClass()

    func showAdmin(window: NSWindow, myClass: MyClass) {
        self.myClass = myClass
        window.makeKeyAndOrderFront(self)
        NSApp.activate(ignoringOtherApps: true)
    }

An instance of this class is instantiated in the App initialization. Later when user clicks on a menu item, I want to show a window and use that value as a singleton for the app, during the time this window is open, also being able to modify myClass. However, the line where the instance variable is declared is being executed multiple times and after the self.myClass = myClassassignment, resetting the object (this is a menubar app that opens a window).

Tried Several things, ex. removing the parameterless constructor from myClass, declaring that variable private and with a "!", adding init methods to the ViewController (without success) and some other failed attempts.

Question How to make myClass a singleton and share it accross the application (i.e. make it available to this window) without reinitializing it?

Christophe
  • 68,716
  • 7
  • 72
  • 138
evilmandarine
  • 4,241
  • 4
  • 17
  • 40

1 Answers1

0

Soo there use to be a bunch of stuff to do this with dispatchOnce and things like that. But now the way I do this is by declaring a shared static variable on my class. This will not handle persistence but it will solve your problem creating your class many times. The shared reference with only be recreated on use after being released. Or if it has never been used before. The class variable is also handy for retrieving the class for many controllers.

class MyClass {

    static let shared = MyClass()

}

class MyViewController: UIViewController {

    let myClass = MyClass.shared

}
jnblanchard
  • 1,182
  • 12
  • 12