My NSTimer (startTimer) works fine. It runs the selected method (runTimer) but whatever code I place in the (runTimer) it does not increment. For example if I run the code as below it prints out 5 times but does not increment x. Any ideas – thanks
- (void)startTimer {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runTimer:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]];
}
- (void)runTimer:(NSTimer *)aTimer {
int x;
x++;
NSLog(@"int x = %i",x);
}
Be careful with static variables in Objective-C methods as suggested by smparkes. They’re shared between all instances of that class, so if you’ve got multiple instances of whatever object this code is from, his answer won’t act the way you expect. You’d be better off with an instance variable, because each instance will have its own variable, without affecting other instances:
In your .h:
Then in your
-runTimer:method:If you are guaranteed that there will only be one instance of whatever this class is (e.g. it’s a singleton), a static variable inside the
-runTimer:method will work, but I’d recommend using an instance variable or @property as it’s better programming practice.