gerbil
gerbil

Reputation: 923

Equivalent of `loadViewIfNeeded` for cocoa?

I'm looking for equivalent function on AppKit for UIKit's loadViewIfNeeded. (this is in order to populate outlets programmatically).

Thank you

Upvotes: 0

Views: 317

Answers (4)

user10711707
user10711707

Reputation: 213

Apple has introduced loadViewIfNeeded() API with no documentation in macOS Sonoma 14.0+.

Upvotes: 0

Jinwoo Kim
Jinwoo Kim

Reputation: 621

NSViewController has private method named -[NSViewController _loadViewIfRequired], maybe equivalent of loadViewIfNeeded.

Upvotes: 0

Lucas Derraugh
Lucas Derraugh

Reputation: 7049

Simply query the view property on NSViewController.

In other words, the equivalent implementation is just:

// Swift
func loadViewIfNeeded() {
    _ = self.view
}
// Obj-C
- (void)loadViewIfNeeded {
   (void)self.view;
}

I don't recommend making this added abstraction, as this is a Cocoa convention that is understood. In my mind, if you're trying to force load the view, it usually is a code smell. Your view should be able to render itself based on the model representing it.

Upvotes: 0

Charles Srstka
Charles Srstka

Reputation: 17060

You just need to reference the view on the NSViewController. Since you didn't specify the language, I'll give the answer in both Objective-C:

(void)viewController.view;

and Swift:

_ = viewController.view

Upvotes: 1

Related Questions