一段时间后显示UIAlertView

Bas*_*sel 2 iphone cocoa-touch uialertview grand-central-dispatch ios

我想在一段时间后显示一个UIAlertView(比如在应用程序中做一些事情后的5分钟).我已经在应用程序关闭或在后台通知用户.但我希望在应用程序运行时显示UIAlertView.

我尝试dispatch_async如下,但警报永远弹出:

[NSThread sleepForTimeInterval:minutes];
 dispatch_async(dispatch_get_main_queue(),
       ^{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" message:@"message!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        [alert release];
       }
       );
Run Code Online (Sandbox Code Playgroud)

另外,我读到线程在30到60分钟后死亡.我想能够在超过60分钟后显示警报.

Jac*_*kin 12

为什么不使用NSTimer,为什么在这种情况下你需要使用GCD?

[NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(showAlert:) userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)

然后,在同一个类中,你会有这样的事情:

- (void) showAlert:(NSTimer *) timer {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" 
                                                     message:@"message!" 
                                                    delegate:self               
                                           cancelButtonTitle:@"Cancel"
                                           otherButtonTitles:nil];
    [alert show];
    [alert release];
}
Run Code Online (Sandbox Code Playgroud)

另外,正如@PeyloW所说,你也可以使用performSelector:withObject:afterDelay::

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"title!" 
                                                 message:@"message!" 
                                                delegate:self               
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:nil];
[alert performSelector:@selector(show) withObject:nil afterDelay:5*60];
[alert release];
Run Code Online (Sandbox Code Playgroud)

编辑你现在也可以使用GCD的dispatch_afterAPI:

double delayInSeconds = 5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title!"
                                                        message:@"message"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release]; //Obviously you should not call this if you're using ARC
});
Run Code Online (Sandbox Code Playgroud)

  • `performSelector:withObject:afterDelay:`将始终在当前线程上执行选择器,并且该对象由当前运行循环保留,直到执行(或取消).实际上,隐式创建了计时器.API将是非常无用的,否则不符合Cocoa内存管理规则.所以,如果你的恐惧是毫无根据的. (3认同)