Objective c 如何在OSX上自动解除NSAlert?

Objective c 如何在OSX上自动解除NSAlert?,objective-c,macos,cocoa,Objective C,Macos,Cocoa,我想创建NSAlert(弹出)显示,然后自动关闭。它同样点击按钮,它显示弹出扫描,找到任何项目后,弹出扫描自动关闭。当弹出窗口显示时,用户无法单击我的应用程序上的任何按钮。我该怎么做?非常感谢。下面的代码将帮助您 - (IBAction)showAlert:(id)sender { //display the alert self.myAlert = [NSAlert alertWithMessageText:@"Sample Test" defaultButton:@"OK"

我想创建NSAlert(弹出)显示,然后自动关闭。它同样点击按钮,它显示弹出扫描,找到任何项目后,弹出扫描自动关闭。当弹出窗口显示时,用户无法单击我的应用程序上的任何按钮。我该怎么做?非常感谢。

下面的代码将帮助您

- (IBAction)showAlert:(id)sender {
    //display the alert
    self.myAlert = [NSAlert alertWithMessageText:@"Sample Test" defaultButton:@"OK" alternateButton:@"DO Nothing" otherButton:@"CANCEL" informativeTextWithFormat:@"TEST",nil];
    [self.myAlert beginSheetModalForWindow:[self window]
                         modalDelegate:self
                        didEndSelector:@selector(errorAlertDidEnd:returnCode:contextInfo:)
                           contextInfo:nil];

    NSArray *buttonArray = [self.myAlert buttons];
    NSLog(@"Button Arrays %@",buttonArray);

    //Close by itself without a mouse click by the user
    //Assuming the Default Button as the Second one "Do Nothing
    NSButton *myBtn = [buttonArray objectAtIndex:2];
    [myBtn performClick:self.myAlert];
}

#导入
@接口NSAlert(自动解除)
-(无效)解雇;
-(void)dismissinafter:(CGFloat)秒完成:(void(^)(void))完成;
@结束
@实施NSAlert(自动解除)
-(无效)解雇{
NSButton*closeButton=self.buttons.lastObject;
如果(关闭按钮){
[关闭按钮性能单击:自我];
}
}
-(void)dismissAfter:(CGFloat)秒完成:(void(^)(void))完成{
__block NSAlert*weakSelf=self;
调度后(调度时间(现在调度时间,秒*NSEC秒),调度获取主队列()^{
[弱者自己解散];
如果(完成){
完成();
}
});
}
@结束

谢谢,但我不想添加任何警报按钮。您能告诉我如何在调用另一个函数时关闭nsalert吗?这对我很有用:[self.myAlert.windoworderout:self];[self.myAlert.window close];
#import <Cocoa/Cocoa.h>

@interface NSAlert(AutoDismiss)
- (void) dismiss;
- (void) dismissAfter: (CGFloat) seconds completion: (void (^)(void)) completion;
@end

@implementation NSAlert(AutoDismiss)

- (void) dismiss {
    NSButton* closeButton = self.buttons.lastObject;
    if (closeButton) {
        [closeButton performClick: self];
    }
}

- (void) dismissAfter: (CGFloat) seconds completion: (void (^)(void)) completion {
    __block NSAlert* weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [weakSelf dismiss];
        if (completion) {
            completion();
        }
    });
}

@end