2009-06-12 16 views
0

NSWindowControllerサブクラスでwindowShouldClose:を使用して、Save、Cancel、およびDo not Saveボタンで閉じる前に変更を保存するかどうかを尋ねるシートをポップアップします。シートの戻り値を使用してウィンドウを閉じるかどうかを決定するにはどうすればよいですか?

私が実行している問題は、戻り値の代わりにbeginSheetModalForWindow:...がデリゲートを使用することです。

私はwindowShouldClose:にNOを返すことができますが、パネルの代理人のコントローラに[self close]を送信すると何も起こりません。

誰かが私にこれを行う方法やサンプルコードの方向を教えてくれますか?

答えて

2

基本的な解決策は、ウィンドウに保存されていない変更について警告されたかどうかを示すブール値フラグをウィンドウに表示することです。 [self close]を呼び出す前に、このフラグをtrueに設定してください。

最後に、windowShouldCloseメソッドで、フラグの値を返します。

+0

ありがとうございます。このパターンを使用しているコード例については、私の答えを見てください。 –

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; 
    } 
} 
関連する問題