0

我想windowShouldClose:在我的 NSWindowController 子类中使用弹出一个表单,询问用户是否要在使用 Save、Cancel 和 Don't Save 按钮关闭之前保存更改。

我遇到的问题是beginSheetModalForWindow:...使用委托而不是返回值。

我可以返回 NO in windowShouldClose:,但是当我发送[self close]到面板委托中的控制器时,什么也没有发生。

有人可以向我解释如何做到这一点或指出一些示例代码的方向吗?

4

2 回答 2

2

基本的解决方案是在窗口上放置一个布尔标志,说明窗口是否警告过未保存的更改。在调用 [self close] 之​​前,将此标志设置为 true。

最后,在 windowShouldClose 方法中,返回标志的值。

于 2009-06-12T02:57:06.767 回答
2

这是我最终使用的代码。

windowShouldCloseAfterSaveSheet_是我的控制器类中的一个实例变量。

记得在 IB 中为控制器设置窗口出口。

- (BOOL)windowShouldClose:(id)window {    
  if (windowShouldCloseAfterSaveSheet_) {
    // User has already gone through save sheet and choosen to close the window
    windowShouldCloseAfterSaveSheet_ = NO; // Reset value just in case
    return YES;
  }

  if ([properties_ settingsChanged]) {
    NSAlert *saveAlert = [[NSAlert alloc] init];
    [saveAlert addButtonWithTitle:@"OK"];
    [saveAlert addButtonWithTitle:@"Cancel"];
    [saveAlert addButtonWithTitle:@"Don't Save"];
    [saveAlert setMessageText:@"Save changes to preferences?"];
    [saveAlert setInformativeText:@"If you don't save the changes, they will be lost"];
    [saveAlert beginSheetModalForWindow:window
                                modalDelegate:self
                               didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) 
                                  contextInfo:nil];

    return NO;
  }

  // Settings haven't been changed.
  return YES;
}

// This is the method that gets called when a user selected a choice from the
// do you want to save preferences sheet.
- (void)alertDidEnd:(NSAlert *)alert 
         returnCode:(int)returnCode
        contextInfo:(void *)contextInfo {
  switch (returnCode) {
    case NSAlertFirstButtonReturn:
      // Save button
      if (![properties_ saveToFile]) {
        NSAlert *saveFailedAlert = [NSAlert alertWithMessageText:@"Save Failed"
                                                   defaultButton:@"OK"
                                                 alternateButton:nil
                                                     otherButton:nil
                                       informativeTextWithFormat:@"Failed to save preferences to disk"];
        [saveFailedAlert runModal];
      }
      [[alert window] orderOut:self];
      windowShouldCloseAfterSaveSheet_ = YES;
      [[self window] performClose:self];
      break;
    case NSAlertSecondButtonReturn:
      // Cancel button
      // Do nothing
      break;
    case NSAlertThirdButtonReturn:
      // Don't Save button
      [[alert window] orderOut:self];
      windowShouldCloseAfterSaveSheet_ = YES;
      [[self window] performClose:self];
      break;
    default:
      NSAssert1(NO, @"Unknown button return: %i", returnCode);
      break;
  }
}
于 2009-06-12T16:27:59.580 回答