2

This seems like a newbie question but I've been struggling with it for a while now. I have some code initialisation that I'd like to run before my app launches.

At the moment I have set up my AppDelegate as follows:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
    func applicationDidFinishLaunching(aNotification: NSNotification)
    {
        runMyInitCode()
    }
}

My problem is that all my object code runs before this. Where is the best place to call initialisation methods before anything else runs?

iphaaw
  • 6,764
  • 11
  • 58
  • 83
  • Related: http://stackoverflow.com/questions/29722672/where-does-a-swift-ios-application-begin-its-life. – Martin R Aug 31 '16 at 15:43
  • Thanks. I have a useful global variable var app = NSApplication.sharedApplication().delegate as! AppDelegate. If I try to access this in override init() then it isn't initialised. If I try to initialise in init() I get errors. Where is the best place to initialise it? – iphaaw Aug 31 '16 at 15:46
  • `NSApplication.sharedApplication().delegate as! AppDelegate` is identical to `class AppDelegate` – vadian Aug 31 '16 at 16:03

1 Answers1

4

You have 4 options (in order of appearance):

  • Override init()
  • Override awakeFromNib()
  • Delegate notification applicationWillFinishLaunching
  • Delegate notification applicationDidFinishLaunching

The best place depends on your needs.

  • If IBOutlets are involved put it not before awakeFromNib.
  • If you are using a view based table view don't put it in awakeFromNib because it could be called multiple times.
  • Registering NSUserDefaults can be put everywhere.
  • Consider also lazy initialization.
  • Consider also Cocoa Bindings.
vadian
  • 274,689
  • 30
  • 353
  • 361