复制 NSDate(需要独立对象) [英] Copying an NSDate (wanting independent objects)

查看:67
本文介绍了复制 NSDate(需要独立对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSDate 符合 NSCopying 协议.根据 NSCopying 协议的文档:

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.

但是,当我这样做时:

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 相同).我错过了什么?如何获得独立对象作为副本?

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

推荐答案

copy 不保证不同的对象指针.功能独立"意味着对原始对象的更改不会反映在副本中,因此对于不可变对象 copy 可以作为 retain (我不知道是否这是有保证的,但可能不是).

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

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

这篇关于复制 NSDate(需要独立对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆