NSTimer因访问错误而崩溃 [英] NSTimer crashes with bad access

查看:134
本文介绍了NSTimer因访问错误而崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following method to update a label which show a simple time up

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

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

I then call this as the action to a button:

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

但是当我运行该应用程序时,出现访问错误,该应用程序崩溃了,有人可以帮我吗?

But when I run the app I get a bad access error and the app crashes, can anyone help me with this?

预先感谢

推荐答案

您是否正在使用ARC?如果不是,请_startTime = [NSDate date];这行会引起您的问题. [NSDate date]返回了一个自动释放对象,如果您不使用ARC(或使用ARC,但将_startTime声明为弱),则_startTime将不保存该对象.

Are you using ARC? If not, _startTime = [NSDate date]; this line will cause your problem. [NSDate date] returned an autorelease object and _startTime will not hold it if you are not using ARC(or using ARC but declared _startTime as weak).

如果是这样,请尝试向其中添加保留项

If so, try to add a retain to it

-(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].

And when you finished your timer, after calling of [_walkRouteTimer invalidate], call [_startTime release].

或更简单,如果对startTime使用属性并将其声明为保留.只需使用点符号即可:

Or even simpler, if you use property for startTime and declared it as retain. Just use dot notation:

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

这篇关于NSTimer因访问错误而崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆