I have my timer being called from the viewDidLoad. For the first time when the timer calls the selector, the expected result is fine. But gradually when the calls are made, the function is somehow called multiple times by the selector. I logged a NSLog which shows that the number of outputs are increasing. I have the code below. Hope it makes the situation clear.
-(void)viewDidLoad
{
remainingTicks = 10;
[self updateLabel];
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(handleTimerTick)
userInfo:nil
repeats:YES];
}
-(void)handleTimerTick
{
remainingTicks--;
[self updateLabel];
if (remainingTicks <= 0) {
[myTimer invalidate];
myTimer = nil;
UIButton *but = [[UIButton alloc] init];
if (answerAt == 0) {
[buttonA setBackgroundColor:[UIColor greenColor]];
}
else if (answerAt == 1) {
[buttonB setBackgroundColor:[UIColor greenColor]];
}
else if (answerAt == 2) {
[buttonC setBackgroundColor:[UIColor greenColor]];
}
else {
[buttonD setBackgroundColor:[UIColor greenColor]];
}
[self performSelector:@selector(next:) withObject:but afterDelay:1.5 ];
}
}
-(void)updateLabel
{
timerLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
}
ViewDidLoadcan be called multiple times during the lifetime of aUIViewController(for example if you get a memory warning and your view is not visible, the controller will release it and reload it next time it’s needed). To handle this behavior properly you should either:A) Test whether the timer exists before creating one (e.g.
if (myTimer == nil) { /* initialize the timer */ })or
B) Clear the timer in your
viewDidUnloadmethod. (This is probably more along the lines of what you want since you most likely don’t want the timer to fire events related to an invisible view).