Objective-C 中复制方法与复制构造函数的参数
我对 Objective-C 的世界比较陌生,并且我已经编写了一个类,我想为其添加创建副本的功能。
来自 Java,我知道我可以编写复制构造函数或克隆方法,后者通常 不推荐。然而,Objective-C 是一种不同的语言,在继续之前,我想了解 Objective-C 中复制方法与复制构造函数的参数。最常用的方法是什么?
I'm relatively new to the world of Objective-C and have a class that I've written to which I'd like to add the ability to create a copy.
Coming from Java, I know that I could either write a copy constructor or a clone method, with the latter commonly not being recommended. However, Objective-C is a different language and before I proceed I'd like to understand the arguments for a copy method versus a copy constructor in Objective-C. What is the most commonly used approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加复制对象功能的推荐方法是实现 NSCopying 协议.
许多基础类也实现 NSCopying。
有关更多信息,请参阅此答案:实现 NSCopying
The recommended way to add the ability to copy objects is by implementing the NSCopying protocol.
Many foundation classes also implement NSCopying.
Refer to this answer for more information: Implementing NSCopying
使用:
-(id)copyWithZone:(NSZone*)zone
,它是NSCopying 协议
的一部分示例:
在 .h 中:
在 .m 中
Use:
-(id)copyWithZone:(NSZone*)zone
which is part of theNSCopying protocol
Example:
in .h:
in .m