Save date - follow-up problem from chapter 11 gold challenge


The gold challenge in chapter 11 was to to push another view controller instance (a “DetailDATEViewController”) onto the navigation stack when the button ChangeDate is tapped in the DetailViewController. This new view controller should have a DatePicker instance to modify the dateCreated property of the selected BNRItem.

To “save” the selected date I added this to the viewWillDisappear: method in the DetailDATEViewController:
[item setDateCreated: changedDate];

This now throws an exception

because in BNRItem.h the types of some properties have changed;
dateCreated is now an NSTimeInterval instead of an NSDate.

So my question is:
How can I “save” the new date selected on the DatePicker (an NSDate) in an BNRItem (that only has an NSTimeInterval variable)?
Can an NSTimeInterval be converted into an NSDate? What would be the reference date?

Thanks for your answers!


You can discover the answer to your question by carefully reading the NSDate Class Reference.

For example:

//  main.m - Calculate a date from its time interval from system's reference date

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterLongStyle];
        [dateFormatter setDateStyle:NSDateFormatterLongStyle];

        // Given date and its time interval
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
        // Calculate and test
        NSDate *date2 = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
        assert ([[date description] isEqualToString:[date2 description]]);
        // Convert and test
        NSLocale *locale = [[NSLocale alloc] init];
        [dateFormatter setLocale:locale];
        assert ([[dateFormatter stringFromDate:date] isEqualToString:[dateFormatter stringFromDate:date2]]);

        // Print
        NSLog (@"%@", [dateFormatter stringFromDate:date]);
        NSLog (@"%@", [dateFormatter stringFromDate:date2]);
    return 0;


ah ok.
Thanks a lot!