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];
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?
Unless you’re using ARC, you need to have ownership of the
NSDateobject 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 ittimeIntervalSinceNow.You can create an owned
NSDatelike so:or by explicitly taking ownership of the return value of
+date:They are equivalent in effect.
Even better (assuming you have a property defined for
_startTime(which you should)) would be using the setter:With the property defined as
retaining, this will handle the memory correctly.