NSAlert beginSheetModalForWindow 不显示警报

NSAlert beginSheetModalForWindow does not display alert

我的 OS X 应用程序的 ViewController 中有以下代码:

   NSAlert *alert = [NSAlert new];
   alert.messageText = @"Connection error";
   alert.informativeText = @"You do not appear to be connected to the internet";
   [alert addButtonWithTitle:@"Third button"];
   [alert addButtonWithTitle:@"Second button"];
   [alert addButtonWithTitle:@"Ok"];

   [alert beginSheetModalForWindow:[[self view] window] completionHandler:^(NSInteger result) {
       NSLog(@"Success");
   }];
// [alert runModal];

当这段代码执行时什么也没有发生。如果我注释掉 beginSheetModalForWindow 行,并取消注释 [alert runModal],则警报会按预期显示。

我在这里做错了什么,它没有显示为 sheet?

我想你是想过早地显示 NSAlert(当 window 正在设置时)尝试添加一个延迟的 perfromselector 看看是否是这种情况

[self performSelector:@selector(delayed) withObject:nil afterDelay:1.0];


-(void)delayed {
    NSAlert *alert = [NSAlert new];
    alert.messageText = @"Connection error";
    alert.informativeText = @"You do not appear to be connected to the internet";
    [alert addButtonWithTitle:@"Third button"];
    [alert addButtonWithTitle:@"Second button"];
    [alert addButtonWithTitle:@"Ok"];

    [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSInteger result) {
        NSLog(@"Success");
    }];
}

如果是这样,请在 window 加载后尝试显示它,例如

- (void)windowDidLoad {
    //code here
}