在AppDelegate中實現的這段代碼有什麼問題?警報很快出現在窗口上,然後消失。 alertDidEnd回調方法永遠不會被調用。beginSheetModalForWindow - 警報窗口消失
我試着清理Xcode 4.6.1中的產品並重建它,但沒有成功。
- (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
[[alert window] orderOut:self];
alertResult = returnCode;
NSLog(@"alertDidEnd called");
}
- (void) showAlert
{
NSAlert *saveAlert = [[NSAlert alloc] init];
[saveAlert setAlertStyle:NSWarningAlertStyle];
[saveAlert setMessageText:messageText];
[saveAlert setInformativeText:informativeText];
[saveAlert addButtonWithTitle:defaultButtonTitle];
[saveAlert addButtonWithTitle:secondButtonTitle];
[saveAlert beginSheetModalForWindow:[self window]
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
}
我自己回答。問題出在applicationShouldTerminate方法的其他地方。
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *) sender
{ if(conditionOK)
doSomeStuff;
else // all changes are not saved
{ [self showAlert];
handleButtonClicked;
}
return NSTerminateNow;
}
在if語句showAlert的其他分支執行,但「迴歸NSTerminateNow」也。應用程序不會等到警報中單擊按鈕。它立即返回。所以我測試一個尚未發佈的響應。
我將修改applicationShouldTerminate方法。
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *) sender
{ if(conditionOK)
doSomeStuff;
return NSTerminateNow;
else
{ [self showAlert];
return NSTerminateCancel;
}
}
alertDidEnd回調方法將測試返回的按鈕,執行作業並根據需要發送終止信號。
目前,我還沒有解決問題,但我知道問題在哪裏。
只是一個問題:beginSheetModalForWindow始終是異步的,還是隻在applicationShouldTerminate的上下文中是異步的?