使用 NSCopying 复制私有实例变量的最佳实践
我可能在这里遗漏了一些明显的东西,但我正在我的一个对象上实现 NSCopying。该对象具有不通过 getter 公开的私有实例变量,因为它们不应该在对象外部使用。
在我的 copyWithZone:
实现中,我需要分配/初始化新实例,而且还设置其状态以匹配当前实例。显然,我可以从 copyWithZone:
内部访问当前私有状态,但无法将其设置到新对象中,因为没有该状态的访问器。
是否有一种标准方法可以解决这个问题,同时仍然保持数据隐私完好无损?
谢谢。
I might be missing something obvious here, but I'm implementing NSCopying on one of my objects. That object has private instance variables that are not exposed via getters, as they shouldn't be used outside the object.
In my implementation of copyWithZone:
, I need alloc/init the new instance, but also set up its state to match the current instance. I can obviously access current private state from inside copyWithZone:
, but I can't set it into the new object, because there are no accessors for that state.
Is there a standard way around this while still keeping data privacy intact?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,你应该总是有吸气剂,即使它们是私有的。你的对象应该只使用访问器访问它自己的ivars(极少数情况除外)。这将为您省去很多内存管理方面的麻烦。
其次,Alex建议使用->;是一种标准方法,尽管这违反了上面的吸气剂规则。该规则有少数例外情况,复制就是其中之一。在这里使用私有设置器仍然是合理的(我以前专门这样做),但我发现由于各种原因,使用 ->经常锻炼得更干净。
要非常小心地确保内存管理正确。如果您需要调用
[super copyWithZone:]
,那么您还应该了解NSCopyObject()
的复杂性以及即使您不使用它也会对您产生怎样的影响你自己吧。我在 “NSCopyObject() 被认为有害。” 中详细讨论了这一点。First, you should always have getters, even if they're private. Your object should only access even its own ivars using accessors (except in a very small number of cases). This will save you a great deal of suffering over memory management.
Second, Alex's suggestion of using -> is a standard approach, even though this violates the getters rule above. There are a small number of exceptions to that rule, and copy is one of. Using private setters here is still reasonable (and I used to do it that way exclusively), but I've found for various reasons that using -> often works out cleaner.
Be very careful to get your memory management correct. If you need to call
[super copyWithZone:]
, then you should also read up on the complexities ofNSCopyObject()
and how it impacts you even if you don't use it yourself. I've discussed this at length in "NSCopyObject() considered harmful."您可以直接访问副本的实例变量。您使用与结构体相同的指针取消引用语法。因此,例如,如果您的课程是这样的:
您可以这样做:
You can access the instance variables of the copy directly. You use the same pointer dereferencing syntax you would use with a struct. So, for example, if your class is this:
You can do this:
一种选择是创建接受私有 iVar 值的自定义初始值设定项。因此,您可以像这样创建它:
实例化副本时,只需使用自定义初始值设定项。
One option is to create a custom initializer that accepts the private iVar values. So you create it like:
When you instantiate the copy, just use the custom initializer.