NSTimer消防特定代码,而不是选择器

时间:2014-11-06 00:25:38

标签: ios objective-c uialertview alert nstimer

我试图在三秒后使UIAlertView自动关闭。 我知道如何制作NSTimer,以及如何单独解除UIAlertView,但我无法弄清楚如何直接从NSTimer运行解雇警报代码,而不是从方法中运行。

这是我的代码(UIAlertView名为alert):

计时器:

[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector( 方法 ) userInfo:nil repeats:NO];

解雇UIAlertView:

[alert dismissWithClickedButtonIndex:-1 animated:YES];

我不能从与创建它的方法不同的方法中解除UIAlertView(除非有人知道这种方法),所以我需要从中调用上面的代码第一种方法,当NSTimer开火时。

提前感谢您的任何帮助/建议。

1 个答案:

答案 0 :(得分:3)

NSTimer仅适用于选择器,无法直接调用方法。

使用dispatch_after代替计时器。

UIAlertView *alert = ... // create the alert view
[alert show];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [alert dismissWithClickedButtonIndex:alert.cancelButtonIndex animated:YES];
});

如果你真的想使用计时器,你可以这样做:

UIAlertView *alert = ... // create the alert view
[alert show];

[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(dismissAlert:) userInfo:alert repeats:NO];

然后你的计时器方法是:

- (void)dismissAlert:(NSTimer *)timer {
    UIAlertView *alert = timer.userInfo;

    [alert dismissWithClickedButtonIndex:alert.cancelButtonIndex animated:YES];
}