NSWindow beginSheet completionHandler not called

2019-05-01 06:41发布

问题:

I am showing a sheet within my main window. I present the sheet using this code:

AddContactWindowController *addContact = [[AddContactWindowController alloc] initWithWindowNibName:@"AddContactWindow"];
addContact.currentViewController = myView;
self.addWindowController = addContact;

[self.view.window beginSheet: addContact.window completionHandler:^(NSModalResponse returnCode) {
    NSLog(@"completionHandler called");
}];

AddContactWindowController is a NSWindowController subclass. It has a view controller within it. Inside the view is a "close" button which invokes this:

[[[self view] window] close];

This does close the window, but the completionHandler from beginSheet is not invoked. This causes me problems down the road.

Is there any particular way we should close the NSWindow sheet for the completion handler to be successfully called? I've also tried [[[self view] window] orderOut:self] but that doesn't work either.

Thanks.

回答1:

You will want to call -endSheet:returnCode: on your window, rather than just ordering it out.



回答2:

You must properly finish the modal session.

I used to call - (void)performClose:(id)sender and stop the modal session in the delegate method.

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

But for a sheet, endSheet looks more appropriate.

self.addWindowController = addContact;

[self.view.window beginSheet:self.addWindowController.window];
...
...
[self.view.window endSheet:self.addWindowController.window];

self.addWindowController = nil