定时UIAlert每60秒发射一次无论我使用什么延迟

时间:2012-12-20 13:54:28

标签: objective-c ios cocoa-touch ios5

我想在用户使用该应用一小时后显示提醒

在app delegate中:

首先我尝试了这个:Displaying UIAlertView after some time

然后我试了

- (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中保留了它,因此它也触发了该方法。谢谢大家

3 个答案:

答案 0 :(得分: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];
}

你应该编辑你的问题,并添加其他信息,因为问题必须在其他地方。

否则,这是你的答案。

答案 1 :(得分: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];
        });

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

答案 2 :(得分: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;
}