Categories
iPhone app

A few iOS gotchas: NSDate copy, sleep and multitask

Reading Time: 2 minutes

I was working on a new app and this app has something to do with timing. Basically I need to record the time between a button being displayed and the time a user touches the button (note they are in two different functions).

NSDate and memory leak
To accomplish this, I am using NSDate class, I declared NSDate * start in the class,
and then in one function, I was doing
start = [NSDate date];

and in the second function, I was doing
NSDate *methodFinish = [NSDate date];
NSTimeInterval intervalTime = [methodFinish timeIntervalSinceDate:start];

But the code above crashes immediately. After some research I believe this has something to do with memory, if we copy (retain) the NSDate as suggested by this thread in iphonedevsdk.com. It worked.

NSDate* now = [NSDate date]; // unretained
start = [now copy]; // retained

Sleep