これは私が使い終わったコードです。
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;
}
}
ありがとうございます。このパターンを使用しているコード例については、私の答えを見てください。 –