Background
I'm adding a TouchBar to an app. I have a few window controllers that should use the same TouchBar design, adopt the same protocol (say AddWindowCommon
), and are designed in their own xib
file.
I designed my TouchBar in a separate xib
file (AddWindowTouchBar
). This way I can set the file to only compile on macOS 10.12.2+ (the versions that support the TouchBar) while the rest of the project deploys on macOS 10.9+. The file owner adopts the AddWindowCommon
protocol and the touchbar keeps a weak reference to it to function properly. Then, to use this touchbar, I override the makeTouchBar
as such:
@available(OSX 10.12.2, *)
open override func makeTouchBar() -> NSTouchBar? {
return AddWindowTouchBar.instanceFromNib(withWindowController: self)
}
That calls the following static function of my AddWindowTouchBar
class:
static func instanceFromNib(withWindowController windowController: AddWindowCommon) -> AddWindowTouchBar {
var objects = NSArray()
Bundle.main.loadNibNamed(xibName, owner: windowController, topLevelObjects: &objects)
// ...
// return the touchbar from `objects`
// ...
}
Question
The problem here is that a class that adopts the AddWindowCommon
protocol has its awakeFromNib:
method called twice: a first time when it is loaded from its own xib
, and a second time when the AddWindowTouchBar
is instantiated using loadNibNamed:owner:
and the window controller is the owner.
To avoid performing the tasks in awakeFromNib:
twice, I could use a simple boolean that ensures the class hasn't been awakened from a nib yet, but I was wondering if there was another cleaner solution that acted on the AddWindowTouchBar
rather than on the AddWindowCommon
protocol-adopters.