Search code examples
cocoansdatenscalendar

Save nsdate to disk


I've looked at the timeIntervalSinceReferenceDate function of NSDate. Can I use this function to store the interval to disk and then return it to NSDate with the same value as the original? I'm wary that the reference or interval could vary between machines and come up differently on another computer?


Solution

  • NSDate can be archived as an NSData instance and NSData can be easily written to / read from disk.

    // Create and store it
    NSDate * date = [NSDate date];
    NSData * dateData = [NSKeyedArchiver archivedDataWithRootObject:date];
    [dateData writeToFile:@"/Some/path/to/file.dat" atomically:NO];
    
    // Now bring it back
    NSData * restoredDateData = [NSData dataWithContentsOfFile:@"/Some/path/to/file.dat"];
    NSDate * restoredDate = [NSKeyedUnarchiver unarchiveObjectWithData:restoredDateData];
    

    No error checking is done. Do better than that. ;-)