使用NSAlert按下哪个按钮的正确方法是什么

时间:2014-04-30 07:19:06

标签: objective-c macos cocoa-touch cocoa

我已向NSAlert对象添加了两个按钮,此时按钮1的返回代码为1001,默认按钮为1000。我需要有效地确定按下给定警报中的哪个按钮而不使用魔术数字。否则会变得混乱。

-(void)showErrorMessage:(NSString*)errorMessage{
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"Error"];
    [alert setInformativeText:errorMessage];
    [alert setAlertStyle:NSCriticalAlertStyle];
    [alert addButtonWithTitle:@"Retake test"];
    [alert addButtonWithTitle:@"Cancel test"];
    [alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:@selector(retakeFingerPrintAlert:returnCode:contextInfo:) contextInfo:nil];
}

- (void)retakeTestAlert:(NSAlert *)alert
                    returnCode:(int)returnCode
                   contextInfo:(void *)contextInfo{
    NSLog(@"clicked %d button\n", returnCode);


    //I want to determine very clearly which button is being pressed in the NSAlert
    //I dont want to work with magic numbers

    //And thus call the below method dependng on the button clicked
    [self onRetakeTest];
}

1 个答案:

答案 0 :(得分:3)

According to Apple's documentation on "addButtonWithTitle:", which you're using:

  

前三个按钮在位置上标识为   NSAlertFirstButtonReturn,NSAlertSecondButtonReturn,   NSAlertThirdButton返回由返回代码参数评估的   模态代表。后续按钮标识为   NSAlertThirdButtonReturn + n,其中n是整数

因此第一个按钮应该等于[NSAlertFirstButtonReturn],这意味着“1000”。第四个按钮应为“1003”。

到目前为止有道理吗?