Copying an NSDate (wanting independent objects)

前端 未结 2 1449
自闭症患者
自闭症患者 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
    

提交回复
热议问题