复制 NSDate(想要独立对象)
NSDate 符合 NSCopying 协议。根据 NSCopying 协议的文档:
a copy must be a functionally independent object with values identical
to the original at the time the copy was made.
但是,当我这样做时:
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"
这两个对象是相同的(相同的对象 ID)。我缺少什么?如何获取独立对象作为副本?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
copy
不保证不同的对象指针。 “功能独立”意味着对原始对象的更改不会反映在副本中,因此对于不可变对象copy
可以用作retain
(我不知道是否虽然这是有保证的,但可能不是)。尝试
date2 = [[NSDate alloc] initWithTimeInterval:0sinceDate:date1]
。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 objectscopy
may work asretain
(I don't know if this is guaranteed though, probably not).Try
date2 = [[NSDate alloc] initWithTimeInterval:0 sinceDate:date1]
.当心!
我最近发现,在 iOS 8.1(.0) 上
[NSDate dateWithTimeInterval:0sinceDate:date1]
返回date1
!甚至 alloc/init 也返回相同的对象。当我创建对象的副本时,深层复制对我来说很重要。稍后,我将时间戳与
[date1 laterDate:date2] == date2
进行比较,如果深度复制不起作用,则该时间戳始终为 true。与
[date1 dateByAddingTimeInterval:0]
相同,我还没有针对 iOS 8.1 的良好解决方案,但请继续搜索并将在此处更新。紧急解决方法可能是使用格式化程序创建日期字符串,然后使用相同的格式化程序从该字符串创建日期。
编辑:情况变得更糟:
Beware!
I recently found out, that on iOS 8.1(.0)
[NSDate dateWithTimeInterval:0 sinceDate:date1]
returnsdate1
! 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:
NSDate 是抽象类。它经常使用 标记指针' 技巧 因此在大多数情况下不可能在同一日期获得不同的对象。在这种情况下,真实的类名称 NSTaggedDate 。
某些日期可能是真实对象(如果标记指针中没有空间)。前任:
NSDate is abstract class. It often uses 'tagged pointer' trick so it will impossible to get different objects for same dates in most cases. Real class name NSTaggedDate in this case.
Some dates could be real object (if there is no space in tagged pointer for it). Ex: