代码之家  ›  专栏  ›  技术社区  ›  Hassan Mahmood

NSTimer因访问错误而崩溃

  •  0
  • Hassan Mahmood  · 技术社区  · 13 年前

    我有以下方法来更新一个标签,该标签显示一个简单的超时

    -(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];
    }
    

    但当我运行应用程序时,我遇到了一个严重的访问错误,应用程序崩溃了,有人能帮我吗?

    提前谢谢

    2 回复  |  直到 13 年前
        1
  •  5
  •   onevcat    13 年前

    你在使用ARC吗?如果不是, _startTime = [NSDate date]; 这条线会引起你的问题。 [NSDate date] 返回了一个autorelease对象,如果您没有使用ARC(或者使用ARC但将_startTime声明为弱),那么_startTime将不会保存它。

    如果是,请尝试添加保留

    -(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;
    
        2
  •  0
  •   JRG-Developer    13 年前

    尝试添加一个异常断点以查看哪一行正在崩溃:

    1) 单击断点选项卡(右二)。。。看起来有点像右箭头或“下一步”按钮

    2) 单击选项卡菜单左下角的“+”

    3) 选择“添加异常断点”

    4) (可选)选择“异常”下拉菜单并更改为“Objective-C”

    5) 选择“完成”

    6) 再次运行您的代码并尝试生成崩溃。。。当你这样做的时候,它有望被这个断点捕获,你会看到哪一行正在崩溃,并能够修复它

    祝你好运