在一段时间后显示UIAlertView

我试图显示一段时间后UIAlertView(如在应用程序中做了5分钟后)。 我已经通知用户,如果应用程序closures或在后台。 但是我想在应用程序运行时显示一个UIAlertView。

我试图dispatch_async如下,但警报是永远popup:

[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分钟后显示警报。

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

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

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

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

这是本地通知的创build。 即使您的应用程序背景不亮或者根本没有运行,您也可以设置一个类似UIAlertView的通知,以便在将来再次出现。

这是一个教程。