Difference between 2 dates in ios seconds

I have an application where the content is displayed to the user. Now I want to know how many seconds the user is viewing this content. So in my header file I declared

NSDate *startTime; NSDate *endTime; 

Then in my view, willappear

  startTime = [NSDate date]; 

Then in my view, WillDisappear

 endTime = [NSDate date]; NSTimeInterval secs = [endTime timeIntervalSinceDate:startTime]; NSLog(@"Seconds --------> %f", secs); 

However, the application sometimes crashes. Sometimes it is a memory leak, sometimes it is a problem with NSTimeInterval, and sometimes it crashes after returning to the content a second time.

Any ideas on fixing this?

+44
ios nsdate nstimeinterval
Nov 01 '13 at 9:59
source share
2 answers

since you do not use ARC when you write

startTime = [NSDate date];

you do not save startTime , so it is freed before calling -viewWillDisappear . Try

startTime = [[NSDate date] retain];

In addition, I recommend using ARC. There should be far fewer errors in managing memory with it than without it.

+13
Nov 01 '13 at 10:44
source share

You must declare a property with persistence for the start date. Your date is freed before you can calculate the time difference.

So announce

 @property (nonatomic, retain) NSDate *startDate - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self setStartDate: [NSDate date]]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; NSLog(@"Seconds --------> %f",[[NSDate date] timeIntervalSinceDate: self.startDate]); } 

Do not forget to clean.

 - (void)dealloc { [self.startDate release]; [super dealloc]; } 
+10
Nov 01 '13 at
source share



All Articles