0

我想在用户使用该应用一个小时时显示警报

在应用委托中:

首先我尝试了这个:一段时间后显示 UIAlertView

然后我尝试了

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self performSelector:@selector(showAlert) withObject:nil afterDelay:3600];

return YES;
}

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

在这两个示例中,我都尝试在after delay. 无论我为延迟做什么,计时器每次都会在一分钟后触发?

更新:这是正确的代码,除了委托之外,我还将它留在了视图控制器的 viewDidLoad 中,因此它也在触发该方法。谢谢大家

4

3 回答 3

3

如果这是你所做的:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    [self performSelector:@selector(showAlert) withObject:nil afterDelay:3600];

    return YES;
}

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

您应该对此进行编辑,并添加其他信息,因为问题必须在其他地方。

否则,这就是你的答案。

于 2012-12-20T14:10:46.390 回答
1

你的代码应该可以工作你确定你没有showAlert在其他地方打电话吗?你也可以试试这个,只是为了确保:

  long long int anHourInNanoSec = 60*60*NSEC_PER_SEC;
  long long int anHourFromNow = dispatch_time(DISPATCH_TIME_NOW, anHourInNanoSec);

  dispatch_after(anHourFromNow, dispatch_get_current_queue(), ^{
            [self showAlert];
        });

顺便说一句,如果应用程序使用一个小时,我不确定您的方法是否会启动。如果应用程序设置为后台,您应该停止计时器。

于 2012-12-20T14:47:27.753 回答
1

抱歉新答案,但评论字段太短,您可以尝试类似:

... 。H

@property (nonatomic, assign) long long int remainingTime; @property (nonatomic, assign) BOOL deamonPaused;

... .m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {

   long long int anHourInNanoSec = 60*60*NSEC_PER_SEC;
   _remainingTime = dispatch_time(DISPATCH_TIME_NOW, anHourInNanoSec);
   _deamonPaused = NO;

   dispatch_queue_t deamonThread = dispatch_queue_create(@"deamonThread", NULL);
   dispatch_async(deamonThread, ^{
            [self launchDeamon];
        });
    dispatch_release(deamonThread);

    return YES; 
}

- (void) launchDeamon{
   while (_remainingTime > 0){
      if (!_deamonPaused)
         _remainingTime -= 5*NSEC_PER_SEC; 
      sleep(5);
   }
   [self showAlert];
}

- (void) applicationDidEnterBackground:(UIApplication *)application{
    _deamonPaused = YES; 
}

- (void) applicationWillEnterForeground:(UIApplication *)application{
   _deamonPaused = NO;
}
于 2012-12-20T16:02:06.583 回答