一段时间后显示UIAlertView

时间:2011-01-04 19:38:19

标签: iphone ios cocoa-touch uialertview grand-central-dispatch

我试图在一段时间后显示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];
       }
       );

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

2 个答案:

答案 0 :(得分:12)

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

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

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

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

此外,正如@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];

编辑您现在还可以使用GCD的dispatch_after API:

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

答案 1 :(得分:0)

这是为本地通知创建的那种东西。您可以设置类似UIAlertView的通知,以便在将来的某个时间出现,即使您的应用程序是后台运行或根本不运行。

Here是一个教程。

相关问题