ios - NSTimer火特定代码,而不是选择器

标签 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的方法不同的方法中释放UIAlertView(除非有人知道该方法),因此,当NSTimer触发时,我需要从中的中调用上述代码,这是第一种方法。

在此先感谢您的帮助/建议。

最佳答案

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];
}

关于ios - NSTimer火特定代码,而不是选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26769732/

相关文章:

c# - 根页面不是 Navigation.NavigationStack 集合的一部分

iPhone - try catch EXC_BAD_ACCESS 错误(似乎是僵尸问题)

objective-c - 无法使用 nil 模型创建 NSPersistentStoreCoordinator

iphone - 显示 UIAlertView 会导致 EXC_BAD_ACCESS

ios - 将文本从 UIAlertView 文本字段传递到自定义单元格标签

ios - 关于 UIGestureRecognizer

ios - 向后迭代for循环?

iphone - 如何在iPhone应用程序中使用post将用户名和密码发送到服务器

ios - AVPlayer 在状态达到 "ReadyToPlay"后仍有延迟

ios - NewsStand,需要时显示推送通知警报 View 吗?