How to write an NSViewController without interface builder on macOS.

Christoffer Winterkvist
hyperoslo
Published in
2 min readFeb 23, 2018
Corinne Kutz — https://unsplash.com/photos/tMI2_-r5Nfo

In a previous post, I wrote about setting a background color to a regular NSView in Cocoa. So, to kick it up a notch, I’d like to share how to make an NSViewController without using nibs/xibs or storyboards. This might seem like a trivial task, and it is. However, without prior knowledge, there is one fundamental pitfall that you can stumble on fairly quickly. Let’s get this show on the road and look at some code.

Just like the previous post, I’ll share how this is done in iOS.

Here we have a subclass of NSViewController called MyViewController. Nothing particularly interesting here, an empty view controller. Easy as pie!

Let’s try the same example for macOS to see what happens.

Looks the same and should act the same? Well, one might assume that, however, this would give you the following log message:

-[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: Apex.ViewController in bundle (null).

Just like stated in the message, your view controller was unable to load resulting in it not being displayed.
The reason for it was looking for a nib file that obviously doesn’t exist. Nibs are the default in macOS as Interface builder is deeply integrated into the architecture of Cocoa; this means that you’ll have to do some extra work to get it working. Luckily it involves minimal changes.

What is missing here is the view controllers view, fixing it we need to implement the loadView method. So let’s take a look at another example where we have a working implementation of an NSViewController without using interface builder.

That’s it, you can now create your view controllers without using NIB’s. Happy coding!

--

--

Christoffer Winterkvist
hyperoslo

random hero at @fink-oslo by day, cocoa vigilante by night, dad at dawn. my life is awesome. Previously @hyperoslo