Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer is not repeating as expected [duplicate]

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?

like image 715
Ohad Regev Avatar asked Dec 08 '22 18:12

Ohad Regev


2 Answers

Use

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

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

like image 74
Andy Avatar answered Dec 11 '22 10:12

Andy


You need to add the timer to a run loop:

[[NSRunLoop mainRunLoop] addTimer:aTimer forMode:NSDefaultRunLoopMode];
like image 40
Stavash Avatar answered Dec 11 '22 09:12

Stavash