NSDate:timeIntervalSinceNow崩溃 [英] NSDate : timeIntervalSinceNow crash

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

问题描述

我想在屏幕上显示自某些事件以来经过的时间.我有一个成员变量

I want to display, on screen, the elapsed time since some event. I have a member variable

NSDate *_startTime;

我这样分配它(并启动一个计时器):

I allocate it (and initiate a timer) like so:

_startTime = [NSDate date];
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(clock) userInfo:nil repeats:YES];

我的时钟函数被很好地调用,但是当我试图找到经过的时间时,我崩溃了,而没有真正的方法来确定发生了什么.我简单地得到 EXC_BAD_ACCESS .以下是我尝试获取自 _startDate 引发异常以来经过的时间的方法:

My clock function gets called fine but when I attempt to find the elapsed time I get a crash with no real way of determining what happens; I simple get EXC_BAD_ACCESS. Below is how I attempt to get the elapsed time since _startDate which throws the exception:

NSTimeInterval secondsElapsed = [_startTime timeIntervalSinceNow];

它在此行崩溃-我环顾四周,这似乎是正确的语法,这是怎么回事?

It crashes on this line - I have looked around and this seems to be the correct syntaax, what is happening here?

推荐答案

除非使用的是ARC,否则您必须拥有存储在 _startTime中的 NSDate 对象的所有权. + [NSDate date] 返回一个您不拥有的对象,它很可能已被释放,因此在您发送该对象时无效 timeIntervalSinceNow .

Unless you're using ARC, you need to have ownership of the NSDate object that you're storing in _startTime. +[NSDate date] returns an object you don't own, and it is likely to have been deallocated and therefore to be invalid by the time you get around to sending it timeIntervalSinceNow.

您可以这样创建自己的 NSDate :

You can create an owned NSDate like so:

// By default, NSDates are initialized with the current date
_startTime = [[NSDate alloc] init];

或通过显式获取 + date 的返回值的所有权:

or by explicitly taking ownership of the return value of +date:

_startTime = [[NSDate date] retain];

它们在效果上是等效的.

They are equivalent in effect.

更好的方法(假设您有一个为 _startTime 定义的属性(应该设置))将使用setter:

Even better (assuming you have a property defined for _startTime (which you should)) would be using the setter:

[self setStartTime:[NSDate date]];

使用定义为 retain ing的属性,可以正确处理内存.

With the property defined as retaining, this will handle the memory correctly.

这篇关于NSDate:timeIntervalSinceNow崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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