Working with multiple Windows Using Interface Builder

1.9k Views Asked by At

How to work with multiple windows in Cocoa? I have created a cocoa application. When I run that application it automatically shows a default window. I've added a button in the window. When I click the button I want to open another window named MySecondWindow which I created in IB..

I created Window controller (MySecondWindowController) for MySecondWindow and linked it to the nib in IB. When I click the button in my main window, I am calling an IBAction that creates an instance of MySecondWindowController and calling the NSApp beginSheet: method with [mySecondWindowObj window]. I am getting the Modal session requires modal window message in NSlog. When I try to print [mySecondWindowObj window] in NSLog, it prints null..

I don't know what to do. What are the necessary things should be done to make this work? I need help..

Thanks..

2

There are 2 best solutions below

0
On BEST ANSWER
YourWindowController* sheet;

[[NSApplication sharedApplication] beginSheet:[sheet window]
                               modalForWindow:[[NSApplication sharedApplication] mainWindow]
                                modalDelegate:nil
                               didEndSelector:nil
                                  contextInfo:nil];

Make sure your window is getting properly instantiated. Make sure the "Visible At Launch" option in IB isn't checked.

EDIT: I just noticed you're loading this window from a separate nib file. Make sure you're loading it properly. Use this:

YourWindowController* sheet = [[YourWindowController alloc] initWithWindowNibName:@"NameOfNibMinusExtension"];

ALSO:

Check and make sure the "File Owner" type is set to your custom window controller's classname, and that it's "window" is set to the window in the Nib.

Right-Click (or Cmd+Click) on File's Owner, and ensure the "window" property is connected to the corresponding window. Also, once again, make sure that the window's "Visible on Launch" is NOT checked.

1
On

Hold down the Control key, click and hold on the button, then drag a line over to MySecondWindow. It'll give you a little black box full of methods: choose makeKeyAndOrderFront:.

What this does is it makes the button (an instance of NSButton) send the makeKeyAndOrderFront: message to the window when you click the button. The button is a subclass of NSControl which implements what is called the target/action system in Cocoa. Interface Builder, when you drag the line, sets the target of the button to be MySecondWindow, and the action to be makeKeyAndOrderFront:. NSButton is then programmed internally to send the action message to the target when it receives a click.

Make sense?