Ios NSTimer未按预期重复

Ios NSTimer未按预期重复,ios,objective-c,nstimer,repeat,Ios,Objective C,Nstimer,Repeat,可能重复: 在我的应用程序中,我有以下设置来使用NSTimer运行操作: 在m。文件: @implementation MYViewController { NSTimer *aTimer; } 然后,当用户单击相关按钮时,我有: - (IBAction)userClick:(id)sender { aTimer = [NSTimer timerWithTimeInterval:1.0 tar

可能重复:

在我的应用程序中,我有以下设置来使用NSTimer运行操作:

在m。文件:

@implementation MYViewController {
      NSTimer *aTimer;
}
然后,当用户单击相关按钮时,我有:

- (IBAction)userClick:(id)sender {
     aTimer = [NSTimer timerWithTimeInterval:1.0 
                                      target:self 
                                    selector:@selector(doSomethingWithTimer:) 
                                    userInfo:nil 
                                     repeats:YES]; 
     //[aTimer fire]; //NSTimer was fired just once.
}
我还有:

-(void)doSomethingWithTimer:(NSTimer*)timer {
     NSLog(@"something to be done");
}
我希望领事每一秒钟都会有一句话说“有事情要做”。计时器甚至不会被调用一次。我已经尝试使用[aTimer fire]启动NSTimer,但它只启动了一次,并且没有像我预期的那样重复


有人能告诉我怎么做吗?

这里的问题是范围。您的
aTimer
变量需要是一个字段,这样一旦您离开
userClick
方法,它就不会得到GC

NSTimer *timer;

...

- (IBAction)userClick:(id)sender {
    if (timer != nil && [timer isValid]) {
        [timer invalidate];
        timer = nil;
    }
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                             target:self 
                                           selector:@selector(doSomethingWithTimer:) 
                                           userInfo:nil 
                                            repeats:YES]; 
}

您需要将计时器添加到运行循环:

[[NSRunLoop mainRunLoop] addTimer:aTimer forMode:NSDefaultRunLoopMode];
使用


这样您就不必手动将其添加到运行循环中。

请检查我的问题--NSTimer*timer--应该在哪里定义?它应该声明为类字段。我熟悉这个选项。在阅读有关它的文章时,我不清楚当我希望NSTimer停止工作时应该做什么。你知道吗?在计时器实例上调用invalidate应该仍然会执行trickI认为是我做的。。。我是否错误地使用了它(请参阅我原始问题中的示例代码)?您使用的是timerWithTimeInterval,而不是ScheduledTimerWithTimeInterval哦。。。愚蠢的我。。。谢谢,成功了。。。
- (NSTimer *)scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: