Creating a custom NSViewController without a nib

cocoa, macos, objective-c

Solution

In short, override `loadView` and set `self.view` to your view. You'll want to give it a frame before you set it.

The default implementation of `loadView` is where it tries to load the nib. You're intended to override this if you don't want that.

Problem

I recently started learning Objective-C and I've run into a slight problem. I'm trying to use a custom view controller without a nib, so the view is created in the code. The view controller itself is created in the AppDelegate. When I run the program, it first displays a default empty window. After I close this window, a second window pops up which correctly contains the view. I obviously don't want that first window to appear, but I don't know what causes it. The only information I could find on this subject was for iOS development, which isn't quite the same. I also get this message of which I'm not really sure what it means: Could not connect the action orderFrontStandardAboutPanel: to target of class MainViewController AppDelegate: ``` - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { mainViewController = [[MainViewController alloc] initWithFrame:_window.frame]; _window.contentView = mainViewController.view; } ``` MainViewController: ``` - (id)initWithFrame:(NSRect)frame { self = [super initWithNibName:nil bundle:nil]; if (self) { [self setView:[[MainView alloc] initWithFrame:frame]]; [self loadView]; } return self; } ```

Original source