2

在我的主 ViewController 中,我有以下代码:

- (IBAction)listFunctions:(id)sender //button clicked
{
    FunctionListController *functionListController = [[FunctionListController alloc] initWithWindowNibName:@"FunctionList"];

    NSWindow *functionListWindow = [functionListController window];

    [NSApp runModalForWindow: functionListWindow];

    NSLog(@"done");
}

FunctionListController是文件的所有者FunctionList.nib和子类,NSWindowController并实现了协议NSWindowDelegate

这里是实现FunctionListController

@implementation FunctionListController

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if(self)
    {
        // Initialization code here.
    }

    return self;
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    self.window.delegate = self;
}

- (void)windowWillClose:(NSNotification *)notification
{
    [NSApp stopModal];
}

@end

当模态窗口关闭时,NSLog(@"done");运行并显示,但是listFunctions完成后,我得到一个 EXC_BAD_ACCESS 错误。

随着NSZombiesEnabled我得到错误[NSWindow _restoreLevelAfterRunningModal]: message sent to deallocated instance

编辑:

我正在使用 ARC。

4

3 回答 3

4

尝试[functionListWindow setReleasedWhenClosed:NO]并强烈引用您的窗口,直到关闭。

于 2016-07-08T05:35:50.373 回答
1

在您的listFunctions方法中,您首先创建一个FunctionListController对象:

- (IBAction)listFunctions:(id)sender //button clicked
{
    FunctionListController *functionListController = [[FunctionListController alloc] initWithWindowNibName:@"FunctionList"];

通过局部变量引用;它将在范围结束时释放(方法本身);

然后,您将获得对 的引用functionListController window并将其作为模态运行:

    NSWindow *functionListWindow = [functionListController window];

   [NSApp runModalForWindow: functionListWindow];

此对象将由NSApp.

但是,该方法退出(runModalForWindow不会阻塞您的线程)并被functionListController释放:

   NSLog(@"done");
}

所以你得到一个悬空引用和一个不再存在的对象拥有的模态窗口。因此,然后崩溃。

简单地说,为你的类创建functionListController一个属性,它就会起作用。strong

您的新listFunctions产品看起来像:

- (IBAction)listFunctions:(id)sender //button clicked
{
    self.functionListController = [[FunctionListController alloc] initWithWindowNibName:@"FunctionList"];
    ...
于 2012-09-02T19:21:38.013 回答
0

functionListWindow是你listFunctions:方法中的一个局部变量。当该方法完成执行时,您将失去对该对象的任何强引用,因此没有任何东西会拥有它并且它将被释放。当您的模态窗口实际关闭时,它会尝试向其委托发送适当的消息,但是这不再存在。

您是否尝试过functionListWindow在主视图控制器上创建实例变量?

于 2012-09-02T19:18:25.037 回答