10

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;
}
user2616316
  • 101
  • 1
  • 3
  • 2
    I guess you are calling loadview 2 times. 2. loadview explicitly. The purpose of -loadView is to, uh, load the view. It's called when you access the view controller's view property and the value of that property is nil. In this case, you're accessing self SetView in your initializer, so that's when -loadView gets called. Again you are calling the loadView specifically. This might be one reason you see 1st time empty or as iOS is loading your application it displays loading image. – Srivathsa Jul 26 '13 at 07:08
  • That's what caused it, thanks! – user2616316 Jul 28 '13 at 17:57
  • Ok great it solved your issue.. Then you can upvote for my comment. – Srivathsa Jul 31 '13 at 08:56

1 Answers1

25

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.

Sam Soffes
  • 14,831
  • 9
  • 76
  • 80
  • This doesn't work. It crashes at with bad access whenever I try to give it a frame – Jacky Wang Jun 01 '15 at 01:05
  • 1
    @JackyWang It does work. You need to declare an `NSView` object inside `loadView`, then set the frame of that object, then set `self.view` to your new view object. In other words, **never** use `self.view.anything` inside `loadView` because `self.view` does not exist yet. –  Dec 10 '16 at 12:07
  • 2
    Note this has changed with macOS 10.10, see the doc for NSViewController. – RickJansen Sep 26 '18 at 20:53