4

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?

Community
  • 1
  • 1
Ohad Regev
  • 5,641
  • 12
  • 60
  • 84
  • 2
    please check my question http://stackoverflow.com/questions/11058571/nstimer-timerwithtimeinterval-not-working – Midhun MP Jan 07 '13 at 12:43

3 Answers3

9

Use

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

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

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Andy
  • 14,260
  • 4
  • 43
  • 56
4

You need to add the timer to a run loop:

[[NSRunLoop mainRunLoop] addTimer:aTimer forMode:NSDefaultRunLoopMode];
Stavash
  • 14,244
  • 5
  • 52
  • 80
  • I'm familiar with this option. When reading about it, I was not clear regarding to what I should do when I wish the NSTimer to stop working. Do you have any idea? – Ohad Regev Jan 07 '13 at 13:03
  • 1
    Calling invalidate on the timer instance should still do the trick – Stavash Jan 07 '13 at 13:06
1

The problem here is scope. Your aTimer variable needs to be a field so it doesn't get GC'd once you leave the userClick method e.g.

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]; 
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
James
  • 80,725
  • 18
  • 167
  • 237