ios - NSTimer递增一次后停止

标签 ios uilabel nstimer object-state

我有一个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/

相关文章:

ios - 设置 UILabel.text 属性会导致线程中的内存泄漏

ios - 如何在 iOS 的钥匙串(keychain)中添加任何 NSString 数据

ios - Microblink:成功读取图像

ios - 无法在 tableView 中设置标签框 :cellForRowAtIndexPath: method

ios - 如何动画一个接一个的 UILabel

objective-c - 在后台工作的计时器

ios - 枚举内存使用

ios - 在 iOS 8.3 中获取 CellID、MCC、MNC、LAC、信号强度、质量和网络

ios - 检测 UILabel 文本的变化

iOS UITextField 和 NSTimer 奇数