如何使用Completion Handler范例创建自定义NSAlert工作表方法

Mie*_*iek 4 objective-c nsalert objective-c-blocks

我已经使用了这个简单的通用方法来实现它,它适用于基于应用程序的对话框,但是我希望在工作表样式对话框中使用相同的功能,并且我很难将它们放在一起.

根据我理解的文档,OS10.9及更高版本中唯一不被弃用的方法是将NSAlert类与完成处理程序进程一起使用.这似乎使得从通用方法返回Bool几乎是不可能的.

我的代码:

-(BOOL)confirm :(NSString*)questionTitle withMoreInfo:(NSString*)addInfo andTheActionButtonTitle:(NSString*)actionType{
    BOOL confirmFlag = NO;

    NSAlert *alert = [NSAlert alertWithMessageText: questionTitle
                                 defaultButton:actionType
                               alternateButton:@"Cancel"
                                   otherButton:nil
                     informativeTextWithFormat:@"%@",addInfo];
    [alert setAlertStyle:1];

    NSInteger button = [alert runModal];

    if(button == NSAlertDefaultReturn){
        confirmFlag = YES;

     }else{

        confirmFlag = NO;
     }

     return confirmFlag;

 }


 The [alert runModal] returns the value I can return.
Run Code Online (Sandbox Code Playgroud)

使用较新的范例,[alert beginSheetModalForWindow:[self window] sheetWindow completionHandler:some_handler]不允许我更新或返回方法结尾的值.我知道为什么,但有没有办法我不想做到这一点.

请告诉我如何创建一个类似于我用于工作表的方法.

谢谢三重

lea*_*lin 6

假设调用的代码confirm:withMoreInfo:andTheActionButtonTitle:是从中调用的validate.

-(void)validate
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:questionTitle];
// fill out NSAlert

[alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
    if(returnCode == NSModalResponseStop)
    {
        confirmFlag = YES;
    }
    else
    {
        confirmFlag = NO;
    }
//Rest of your code goes in here.
}];

}
Run Code Online (Sandbox Code Playgroud)

你的代码的其余部分必须是INSIDE完成块.