Difference between 2 dates in seconds ios

34,902

Solution 1

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

Solution 2

You should declare a property with retain for the start date. Your date is getting released before you can calculate the time difference.

So declare

@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]);
}

Don't forget to cleanup.

- (void)dealloc
{
    [self.startDate release];
    [super dealloc];
}
Share:
34,902

Related videos on Youtube

Adam Altinkaya
Author by

Adam Altinkaya

Updated on September 08, 2020

Comments

  • Adam Altinkaya
    Adam Altinkaya over 3 years

    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?

    • Adam Altinkaya
      Adam Altinkaya over 10 years
      I've edited the code as above... The log I sometimes get is: -[__NSCFType timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0xbbf7c10'
    • Adam Altinkaya
      Adam Altinkaya over 10 years
      Not using ARC, I've tried releasing them in the dealloc method and in the viewWillDisappear, but still get the same problem?