Reputation: 6942
How to do it? I simply want to load a window and show it in front of the main window.
NSWindowController* controller = [[NSWindowController alloc] initWithWindowNibName: @"MyWindow"];
NSWindow* myWindow = [controller window];
[myWindow makeKeyAndOrderFront: nil];
This code shows the window for one moment and then hides it. IMHO this is because I don't keep reference to the window (I use ARC
). [NSApp runModalForWindow: myWindow];
works perfectly but I don't need to show it modally.
Upvotes: 3
Views: 3644
Reputation: 22948
You should likely do something similar to the following, which creates a strong
reference to the NSWindowController
instance you create:
.h:
@class MDWindowController;
@interface MDAppDelegate : NSObject <NSApplicationDelegate> {
__weak IBOutlet NSWindow *window;
MDWindowController *windowController;
}
@property (weak) IBOutlet NSWindow *window;
@property (strong) MDWindowController *windowController;
- (IBAction)showSecondWindow:(id)sender;
@end
.m:
#import "MDAppDelegate.h"
#import "MDWindowController.h"
@implementation MDAppDelegate
@synthesize window;
@synthesize windowController;
- (IBAction)showSecondWindow:(id)sender {
if (windowController == nil) windowController =
[[MDWindowController alloc] init];
[windowController showWindow:nil];
}
@end
Note that rather than sending the makeKeyAndOrderFront:
method directly to the NSWindowController
's NSWindow
, you can just use NSWindowController
's built-in showWindow:
method.
While the above code (and sample project below) use a custom subclass of NSWindowController
, you also use a generic NSWindowController
and create the instance using initWithWindowNibName:
(just make sure the File's Owner of the nib file is set to NSWindowController
rather than a custom subclass like MDWindowController
).
Sample project:
http://www.markdouma.com/developer/MDWindowController.zip
Upvotes: 1
Reputation: 5589
Yes, with ARC if you don't hold a reference to the window it will be torn down as soon you as you exit the routine you were in. You need to hold a strong reference to it in an ivar. [NSApp runModalForWindow: myWindow]
is different because the NSApplication
object holds a reference to the window as long as it is being run modally.
Upvotes: 6