0

I'm developing a macOS application that only consists of a menu bar icon.

I have a xib file (MenuBarMenu.xib) with the menu and a corresponding controller(MenuBarMenuController.swift) that puts it in menubar.

enter image description here

I want to inject dependencies in this controller, either manually or with Swinject.

So to do this I thought I could load the xib file programmatically from AppDelegate:

 func applicationDidFinishLaunching(_ aNotification: Notification) {
        let controller = MenuBarMenuController(nibName: "MenuBarMenu", bundle: nil)
        controller.someDependency = Test()
 }

But it looks like controller is being instantiated automatically by NSApplication before reaching applicationDidFinishLaunching.

What I've tried:

  1. Removed NSMainNibFile from info.plist
  2. Removed NSMainStoryboardFile from info.plist
  3. Cleared Main Interface setting in project settings
  4. Added LSUIElement = yes
  5. Used custom main.swift to make sure my AppDelegate is called.

If xib file is there, it's called before AppDelegate. When I delete it, there are no runtime errors.

My question is: how can I inject a dependency in this controller?

undsoft
  • 789
  • 2
  • 12
  • 21
  • Be sure the controller already loaded (viewDidLoad). If loaded, you can perform inject dependency. It seems to be you have created a controller, but not pushed to any controller. – Agisight Apr 12 '19 at 10:19
  • Did you create the project from scratch? – Willeke Apr 12 '19 at 10:29
  • 1
    No, I used a Cocoa App template. – undsoft Apr 12 '19 at 10:30
  • Which one? Did you add MenuBarMenu.xib? – Willeke Apr 12 '19 at 10:32
  • macOS -> Cocoa App -> Use storyboard, Use coredata, but I've heavily modified it since. I now have MenuBarMenu.xib that I've added and a storyboard which I use for windows. Storyboard is referenced in info.plist in any way. – undsoft Apr 12 '19 at 10:34
  • There are two controllers: one created by `MenuBarMenuController(nibName: "MenuBarMenu", bundle: nil)` and the object in the xib. – Willeke Apr 12 '19 at 10:35
  • Fair enough, but is there a way for me to inject any dependencies in the controller from xib? Or reorganize the xib/code so that I can make an injection in this scenario. – undsoft Apr 12 '19 at 10:37
  • Did you add `let controller = MenuBarMenuController` to access the controller? Where do you instantiate `MenuBarMenuController`? – Willeke Apr 12 '19 at 10:43
  • Well, I tried to instantiate one in AppDelegate, though I'm not sure if it actually does what I want it to do. And the actual MenuBarMenuController is instantiated by the framework when xib file is loaded. – undsoft Apr 12 '19 at 10:46

1 Answers1

0

While I didn't figure out how to inject a dependency in my particular scenario, I was able to work around it by using a storyboard instead of a xib file. Then with the help of SwinjectStoryboard I can make the injection.

undsoft
  • 789
  • 2
  • 12
  • 21