So, let's say I've got a method like this, which is used to check if document has been modified, before actually closing it :

- (BOOL) canCloseDocument:(id)document
{
     if ([document modified])
     CONFIRM_ALERT(@"Close Document", 
                      @"Are you sure you want to close this document?", 
                      [[core browser] window], 
                      @selector(confirm:code:context:),
                      nil);
     else
          return YES;
}

In this case the confirm:code:context: method will be called and NOTHING will be returned by canCloseDocument.

Here's my CONFIRM_ALERT definition :

#define CONFIRM_ALERT(X,Y,Z,W,V) \
NSAlert* confirmAlert = [NSAlert alertWithMessageText:X \
defaultButton:@"OK" \
alternateButton:@"Cancel" \
otherButton:nil \
informativeTextWithFormat:Y]; \
[confirmAlert beginSheetModalForWindow:Z \
modalDelegate:self \
didEndSelector:W \
contextInfo:V];

Question :

How could I do it so that the Alert sheet is displayed, and the value (OK pressed? Cancel pressed?) is retrieved within the same method (canCloseDocument:), so that it can return either YES or NO?

有帮助吗?

解决方案

Sheets are window-modal, not application-modal. That means that they don't operate the way you're hoping. The sheet gets displayed, but then flow of execution has to return to the main event loop so that the user can continue to operate on other windows of your app.

If you want an answer before you return, you have to use a modal alert. Create the alert and then invoke -runModal on it, instead of -beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:.

However, that prevents the user from doing anything else with your app until they dismiss the modal alert. Note, that's not just inherent in a modal alert, it's inherent in your desire for -canCloseDocument: to not return until it has an answer. That implies that flow of execution is not returned to the main event loop, which is what allows interaction with your app.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top