Search code examples
iosuilabelnstimerobject-state

NSTimer stops after incrementing once


I have an NSTimer which I want to update a label every second. My code is:

- (IBAction)OnClickEmergencyButton:(id)sender
{
    emergencyAlertTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(emergencyTimer) userInfo:nil repeats:YES];
    [emergencyAlertTimer fire];
}

- (void)emergencyTimer
{
    int i = 0;
    _emergencyAlertTriggerTimerLabel.text = [NSString stringWithFormat:@"%d", ++i];
}

When I ran it, the label displayed "1" initially and then stopped.

I want the label to continuously count up every second, like "1", "2", "3", ...


Solution

  • There is no issue with your timer. The issue is with the variable declaration inside the emergencyTimer, you declared it as a local variable. So each time when the timer fires the variable will be initialized to 0 again. So declare the variable as static, so that it can preserve the value.

    Change the method like:

    -(void)emergencyTimer
    {
        static int timeValue = 0;
        _emergencyAlertTriggerTimerLabel.text = [NSString stringWithFormat:@"%d",++timeValue];
    }
    

    Why static variable and Why not instance variable ?

    I didn't used instance variable, for keeping the variable "Scope" safe. If I put it as an instance variable, it can be accessed by other methods of the same class, if there is no need of that functionality, I think using a static variable will be better.