簡體   English   中英

NSTimer消防特定代碼,而不是選擇器

[英]NSTimer fire specific code, not selector

我試圖在三秒后使UIAlertView自動關閉。 我知道如何制作NSTimer,以及如何單獨解除UIAlertView,但我無法弄清楚如何直接從NSTimer運行dismiss-alert代碼,而不是從方法運行。

這是我的代碼(UIAlertView被命名為alert ):

計時器:

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

關閉UIAlertView:

[alert dismissWithClickedButtonIndex:-1 animated:YES];

我不能從除創建它(除非有人知道的方式來表示)的一個不同的方法駁回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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM