我有一个NSTimer
,我想每秒更新一次标签。我的代码是:
- (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];
}
当我运行它时,标签最初显示为“1”,然后停止。
我希望标签持续每秒计数,例如“1”,“2”,“3”,...
最佳答案
您的计时器没有问题。问题在于emergencyTimer
中的变量声明,您将其声明为局部变量。因此,每次在计时器触发时,变量都会再次初始化为0。因此,将变量声明为静态变量,以便可以保留该值。
更改方法如下:
-(void)emergencyTimer
{
static int timeValue = 0;
_emergencyAlertTriggerTimerLabel.text = [NSString stringWithFormat:@"%d",++timeValue];
}
为什么使用静态变量,为什么不使用实例变量?
我没有使用实例变量来保持变量“范围”的安全。如果将其作为实例变量,则可以由同一类的其他方法访问,如果不需要该功能,我认为使用静态变量会更好。
关于ios - NSTimer递增一次后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22320061/