NSWindowController's window released immediate

2020-03-26 03:51发布

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条回答
别忘想泡老子
2楼-- · 2020-03-26 04:02

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
查看更多
登录 后发表回答