Search code examples
cocoanswindownswindowcontroller

Doesn't initWithWindowNibName Set the window Field


I am trying to the the following code to work. It does what's expected the first time and opens up a window and makes it the front window, but when it is called subsequent times, orderFront: doesn't work because window is nil. Why doesn't initWithWindowNibName: set the window field of the NSWindowController object that is returned from initWithNibName:?

//
//  CustomerCard.m
//  POSWonder
//
//  Created by kaydell on 2/26/12.
//  Copyright 2012 Kaydell Leavitt. All rights reserved.
//

#import "CustomerCard.h"

@implementation CustomerCard

// declare customerCard as a static variable
static CustomerCard* customerCard;

+(void) show {

    // if the customer card isn't instantiated, then instantiate it
    if (customerCard == nil) {
        customerCard = [[CustomerCard alloc] initWithWindowNibName:@"CustomerCard"];
        if (!customerCard.window) {
            NSLog(@"Why is window nil here?"); // <<<<<<<<<<< This line gets called <<<<<
        }
    }

    // show the customer card and make it the front window
    [customerCard showWindow:self];
    [customerCard.window orderFront:self]; // <<<<<<<< This line doesn't seem to do anything

}

-(void) dealloc {
    customerCard = nil;
    [super dealloc];
}

@end

Solution

  • I know that this is an old question, but I wanted to answer my own question anyways.

    • I think that my using static variables and a singleton for the Customer Card is not a good idea.

      // declare customerCard as a static variable
      static CustomerCard* customerCard;

    It seems to me now that whenever you use static variables, you are defeating the purpose of object-oriented programming. Maybe the user wants to have more than one customer card to view more than one customer in different windows.

    • My idea of using the class method: "show", to always show the same Customer Card, is not a good idea either. I think now that the user should have the freedom to choose "New Customer Card" from the "File" menu, or go back to an existing Customer Card using the "Window" menu.

    That's what I think now.