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?
Asked
Active
Viewed 6,492 times
9

JWWalker
- 22,385
- 6
- 55
- 76

the Reverend
- 12,305
- 10
- 66
- 121
2 Answers
34
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. ;-)

Joshua Nozzi
- 60,946
- 14
- 140
- 135
-
1NSKeyedArchiver can also directly write to a file without NSData. – Jun 08 '11 at 21:12
-
1+archiveRootObject:toFile: - true. – Joshua Nozzi Jun 08 '11 at 21:20
-
Doesn't work, It says: -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL – Idan Aug 02 '12 at 00:28
-
Then what's wrong with the NSData instance you're handing it? – Joshua Nozzi Aug 02 '12 at 01:31
-
Thank you so much! You saved me! I'm writing an app and I couldn't figure out for the life of me why my NSDate wasn't loading! =) Again, thank you so much! =) – TomLisankie Sep 04 '12 at 04:29
2
Alternatively, if you want to store the result of timeIntervalSinceReferenceDate
you can store it in an NSNumber as a double and then save that to disk using Joshua's NSKeyedArchiver method.

Francis McGrew
- 7,264
- 1
- 33
- 30
-
Or you could just write the 8 bytes of the double without bothering with archiving. – JWWalker Mar 09 '17 at 17:06