Copying an NSDate (wanting independent objects)

会有一股神秘感。 提交于 2019-12-09 15:54:21

问题


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?


回答1:


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].




回答2:


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


来源:https://stackoverflow.com/questions/7885669/copying-an-nsdate-wanting-independent-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!