Search code examples
iosobjective-cnstimerrepeat

NSTimer is not repeating as expected


Possible Duplicate:
NSTimer timerWithTimeInterval: not working

In my app I have the following settings to run an action with a NSTimer:

in the m. file:

@implementation MYViewController {
      NSTimer *aTimer;
}

Than, when the user clicks the relevant button I have:

- (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.
}

and I also have:

-(void)doSomethingWithTimer:(NSTimer*)timer {
     NSLog(@"something to be done");
}

I would expect to have a line in the consul saying "something to be done" every one second. The timer is not called even once. I already tried firing the NSTimer using [aTimer fire] but it fires it just once and doesn't repeat as I expect.

Can anyone direct me to how to approach this?


Solution

  • Use

    - (NSTimer *)scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
    

    and then you won't have to add it to run loop manually.