I have an app where content is displayed to the user. I now want to find out how many seconds a user actually views that content for. So in my header file, I've declared an
NSDate *startTime; NSDate *endTime;
Then in my viewWillAppear
startTime = [NSDate date];
Then in my viewWillDisappear
endTime = [NSDate date]; NSTimeInterval secs = [endTime timeIntervalSinceDate:startTime]; NSLog(@"Seconds --------> %f", secs);
However, the app crashes, with different errors sometimes. Sometimes it's a memory leak, sometimes it's a problem with the NSTimeInterval, and sometimes it crashes after going back to the content for a second time.
Any ideas on to fix this?
Getting difference between two dates is easy. You should know how to play between the dates. We will be using DateFormatter class for formatting the dates. Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.
We have the startDate and endDate which we can convert both to timestamps in milliseconds with getTime . Then we subtract the timestamp of endDate by the timestamp of startDate . This will return the timestamp difference in milliseconds. So we divide the difference by 1000 to get the difference in seconds.
date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear! - xmas!) This is the number of seconds between the two dates.
NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"]; NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"]; NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1]; int numberOfDays = secondsBetween / 86400; NSLog(@"There are %d days in between the two dates.", numberOfDays);
since you are not using ARC, when you write
startTime = [NSDate date];
you do not retain startTime
, so it is deallocated before -viewWillDisappear
is called. Try
startTime = [[NSDate date] retain];
Also, I recommend to use ARC. There should be much less errors with memory management with it, than without it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With