iphone - NSTimer 因访问错误而崩溃

标签 iphone ios nstimer exc-bad-access

我有以下方法来更新显示简单时间的标签

-(void)updateTimeLabel:(NSTimer *)timer{
    NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:_startTime];

    NSInteger seconds = secondsSinceStart % 60;
    NSInteger minutes = (secondsSinceStart / 60) % 60;
    NSInteger hours = secondsSinceStart / (60 * 60);
    NSString *result = nil;
    if (hours > 0) {
        result = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    }
    else {
    result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    }

    _totalTime = result;
    _totalTimeLabel.text = result;
}

然后我将其称为对按钮的操作:

-(IBAction) startTimer{
    _startTime = [NSDate date];
    _walkRouteTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimeLabel:) userInfo:nil repeats:YES];
    [_walkRouteTimer fire];
}

但是当我运行该应用程序时出现访问错误并且应用程序崩溃,有人可以帮助我解决这个问题吗?

提前致谢

最佳答案

您在使用 ARC 吗?如果不是,_startTime = [NSDate date]; 这一行将导致您的问题。 [NSDate date] 返回了一个自动释放对象,如果您不使用 ARC(或使用 ARC 但将 _startTime 声明为弱),_startTime 将不会保存它。

如果是,尝试给它加一个retain

-(IBAction) startTimer{
    //_startTime = [NSDate date]
    _startTime = [[NSDate date] retain];
    _walkRouteTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimeLabel:) userInfo:nil repeats:YES];
    [_walkRouteTimer fire];
}

当你完成计时器时,在调用 [_walkRouteTimer invalidate] 之后,调用 [_startTime release]

或者更简单,如果您为 startTime 使用属性并将其声明为保留。只需使用点符号:

-(IBAction) startTimer{
    //_startTime = [NSDate date]
    self.startTime = [NSDate date];
    _walkRouteTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimeLabel:) userInfo:nil repeats:YES];
    [_walkRouteTimer fire];
}
...
//After [_walkRouteTimer invalidate]
self.startTime = nil;

关于iphone - NSTimer 因访问错误而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212071/

相关文章:

iphone - 无法在 objective-c 的表中插入记录

ios - imagePickerController 选择照片时出错

iphone - 循环 UIScrollView 但继续减速

ios - Xcode 构建失败 : Requested but did not find extension point

ios - 企业发展概况VS企业分布概况

ios - iTunes 中一个游戏的多个类别

ios - 在 NSRunLoop 中取消 NSTimer

swift : Extra Argument in call with scheduledTimerWithTimeInterval

iphone - 披露指标消失?

使用 NSTimer 通过单元测试后,iOS 逻辑单元测试目标崩溃