NSTimer - 为什么scheduledTimerWithTimeInterval工作,但initWithFireDate不工作?

时间:2013-10-16 13:41:57

标签: objective-c

根据需要,每60秒重复调用我的选择器:

autoDeleteTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:[SimpleDB class] selector:@selector(autoDelete:) userInfo:nil repeats:YES];

下一行根本不会调用它。不是最初也不是60秒后:

autoDeleteTimer = [[NSTimer alloc] initWithFireDate: [NSDate dateWithTimeIntervalSinceNow:1] interval:60 target:[SimpleDB class] selector:@selector(autoDelete:) userInfo:nil repeats:YES];

任何人都可以解释原因吗?感谢。

1 个答案:

答案 0 :(得分:3)

您需要将第二个计时器添加到主循环中:

[[NSRunLoop mainRunLoop] addTimer: autoDeleteTimer forMode:NSDefaultRunLoopMode];

从方法文档中:

- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
  

返回值:   接收器,初始化,当添加到运行循环时,它将   如果重复是“是”,则在此之后每隔一秒开火。

     

您必须使用addTimer:forMode:将新计时器添加到运行循环中。   在触发时,计时器将消息aSelector发送到目标。 (如果   计时器配置为重复,不需要随后重新添加   运行循环的计时器。)

NSTimer Apple Doc