9

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;
}
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. Commented Jul 26, 2013 at 7:08
  • That's what caused it, thanks! Commented Jul 28, 2013 at 17:57
  • Ok great it solved your issue.. Then you can upvote for my comment. Commented Jul 31, 2013 at 8:56

1 Answer 1

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work. It crashes at with bad access whenever I try to give it a frame
@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.
Note this has changed with macOS 10.10, see the doc for NSViewController.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.