Copying an NSDate (wanting independent objects)

前端 未结 2 1464
自闭症患者
自闭症患者 2021-02-20 12:04

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

a copy must be a functionally independent object with values ident         


        
相关标签:
2条回答
  • 2021-02-20 12:29

    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
    
    0 讨论(0)
  • 2021-02-20 12:33

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

    0 讨论(0)
提交回复
热议问题