Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying an NSDate (wanting independent objects)

NSDate conforms to NSCopying protocol. According to the documentation for NSCopying protocol:

a copy must be a functionally independent object with values identical
to the original at the time the copy was made.

But, when I do this:

NSDate *date1 = [NSDate date];
NSDate *date2 = [date1 copy];
NSLog(@"result: date1 0x%x  date2 0x%x", (int)date1, (int)date2);
// "result: date1 0x2facb0  date2 0x2facb0"

The two objects are identical (same object id). What am I missing? How do I get an independent object as a copy?

like image 975
Jeff Avatar asked Oct 25 '11 06:10

Jeff


2 Answers

Beware!

I recently found out, that on iOS 8.1(.0) [NSDate dateWithTimeInterval:0 sinceDate:date1] returns date1! Even the alloc/init returns the same object.

The deep-copy was important for me, as I create copies of objects. Later I compare the timestamps with [date1 laterDate:date2] == date2 which will always be true, if the deep-copy doesn't work.

Same for [date1 dateByAddingTimeInterval:0]

I have no good solution for iOS 8.1, yet, but keep searching and will update here. An emergency-workaround could be to create a date-string with a formatter, and then create a date from the string with the same formatter.

Edit: It get's even worse:

NSString *date1String = [iso8601DateFormatter stringFromDate:date1];
date2 = [iso8601DateFormatter dateFromString:date1String];

(lldb) p date1
(NSDate *) $0 = 0xe41ba06fd0000000 2014-11-03 01:00:00 CET
(lldb) p date2
(NSDate *) $1 = 0xe41ba06fd0000000 2014-11-03 01:00:00 CET
like image 172
Felix Lieb Avatar answered Nov 18 '22 17:11

Felix Lieb


copy does not guarantee different object pointer. “Functionally independent” means that changes to the original object will not be reflected in the copy, and thus for immutable objects copy may work as retain (I don't know if this is guaranteed though, probably not).

Try date2 = [[NSDate alloc] initWithTimeInterval:0 sinceDate:date1].

like image 22
hamstergene Avatar answered Nov 18 '22 15:11

hamstergene