swift - 检查 NSAlert 当前是否显示

标签 swift macos cocoa nsalert

我正在使用 NSAlert 在我的应用程序的主屏幕上显示错误消息。 基本上,NSAlert 是我的主视图 Controller 的一个属性

class ViewController: NSViewController {

    var alert: NSAlert?

    ...

}

当我收到一些通知时,我会显示一些消息

func operationDidFail(notification: NSNotification)
{
    dispatch_async(dispatch_get_main_queue(), {

        self.alert = NSAlert()
        self.alert.messageText = "Operation failed"
        alert.runModal();
    })
}

现在,如果我收到多个通知,每个通知都会显示警报。我的意思是,它与第一条消息一起出现,我点击“确定”,它消失,然后与第二条消息一起再次出现,等等……这是正常行为。

我想要实现的是避免这一系列错误消息。其实我只关心第一个。 有没有办法知道我的警报 View 当前是否正在显示? 类似于 iOS 的 UIAlertView 上的 alert.isVisible 吗?

最佳答案

根据您的代码,我怀疑通知是在后台线程中触发的。在这种情况下,任何检查警报现在是否可见的检查都无济于事。在第一个 block 完成之前,您的代码不会开始执行后续 block ,因为 runModal 方法将阻塞,以模式模式运行 NSRunLoop

要解决您的问题,您可以引入原子 bool 属性并在 dispatch_async 之前检查它。

Objective-C 解决方案:

- (void)operationDidFail:(NSNotification *)note {
    if (!self.alertDispatched) {
        self.alertDispatched = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.alert = [NSAlert new];
            self.alert.messageText = @"Operation failed";
            [self.alert runModal];
            self.alertDispatched = NO;
        });
    }
}

使用 Swift 的相同代码:

func operationDidFail(notification: NSNotification)
{
    if !self.alertDispatched {
        self.alertDispatched = true
        dispatch_async(dispatch_get_main_queue(), {
            self.alert = NSAlert()
            self.alert.messageText = "Operation failed"
            self.alert.runModal();
            self.alertDispatched = false
        })
    }
}

关于swift - 检查 NSAlert 当前是否显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36157382/

相关文章:

objective-c - NSStackView 只显示最新的自定义 View

ios - 设置解析查询的缓存策略会导致应用程序崩溃

objective-c - 当实例化对象时,向已释放的对象发送 NSKeyValueNotifyObserver 消息时如何发生 BAD ACCESS

linux - IBM Swift 沙盒 : Running NSURLSession: Error running code: unknown error code 132

macos - gcc 不工作 - Xcode 3.2.6 - 雪豹

macos - Haskell openGL 和 GLUT 在 Mac OS X 上卡住?我可以在 GLUT 上使用 GLFW 吗?

macos - 将 openmp (llvm) 与 sourceCpp 一起使用时找不到 math.h

cocoa - 在 PyObjC 中的 NSImage 上绘制文本时出错

swift - 有什么方法可以在 tvOS 中获取屏幕的 SIZE?

ios - swift 中的 dismissViewControllerAnimated 抛出异常