问题
I'm trying to open a window using a NSWindowController in my app delegate. I created a basic NSWindowController with an associated NIB and try to show the window that way:
@implementation MyAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Show the main window from a separate nib
MyWindowController * theWindowController = [[MyWindowController alloc] initWithWindowNibName:@"MyWindowController"];
[theWindowController showWindow:self];
}
@end
When I launch the app, the window of MyWindowController only appears for a fraction of second (seems to be released as soon as it launches).
Using ARC, how could I force the window to stick around and not be flushed right away? I do not use NSDocuments and I want to be able to use many of these MyWindowController concurrently.
回答1:
You need to add a property to your app delegate (or some other object that's going to stick around for the lifetime of your app) that retains theWindowConroller. For example:
@interface MyAppDelegate : NSObject
@property (strong, nonatomic) MyWindowController * windowController;
@end
Then set this property when you initialize the window controller.
@implementation MyAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Show the main window from a separate nib
self.windowController = [[MyWindowController alloc] initWithWindowNibName:@"MyWindowController"];
[theWindowController showWindow:self];
}
@end
来源:https://stackoverflow.com/questions/11677043/nswindowcontrollers-window-released-immediately