我可以使用同一个 NSZone 两次吗?
第一次尝试实现 NSCopying,我对 NSZone 的细微之处有一个疑问:
- (id)copyWithZone:(NSZone *)zone {
MyClass *copy = [[[self class] allocWithZone:zone] init];
copy.array = [[self.array mutableCopyWithZone:zone] autorelease];
return copy;
}
在这个例子中,我使用 NSZone 两次:第一次分配对象,然后再次分配数组的副本。这合法吗?有必要吗?我可以简单地执行 mutableCopy,并且我也在考虑使用 -initWithArray:copyItems: 作为可能的替代方案。
最好的办法是什么?对于“我需要生成的数组的对象是浅拷贝还是深拷贝?”这个问题,请随意选择任何一种方式。对我来说关键是两次使用 NSZone 是否安全。
Trying to implement NSCopying for the first time, and I have a question about the subleties of NSZone:
- (id)copyWithZone:(NSZone *)zone {
MyClass *copy = [[[self class] allocWithZone:zone] init];
copy.array = [[self.array mutableCopyWithZone:zone] autorelease];
return copy;
}
In this example, I am using the NSZone twice: first to allocate the object and then again to allocate the copy of the array. Is this legal? Is it necessary? I could simply do mutableCopy, and I'm also looking at using -initWithArray:copyItems: as a possible alternative.
What's the best way? Feel free to go either way on the question of "do I need the resulting array's objects to be a shallow or deep copy?" The key for me is whether it is safe to use NSZone two times.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从同一个区域创建多个对象正是区域被发明的目的。这个想法是,您可以创建一个区域,并从该区域创建一个或多个对象(它们可能会创建任何相关对象),然后您可以销毁该区域,从而销毁其中的所有对象。
问题在于,这与引用计数(即所有权)的概念相当不相容。如果你吹走一个包含一个或多个物体的区域,而这些物体仍然拥有(即,期望仍然能够使用),事情就会崩溃。如果在您销毁该区域时,所有这些对象都已被其所有所有者释放,那么它们已经一次被释放一个,因此该区域不会完成任何任务,因此是不必要的。
因此, 区域已被取消,因此,尽管您可能仍然更喜欢按照风格进行操作为了保持一致性,它不会对运行时发生的情况产生任何显着差异。
Creating multiple objects from the same zone is exactly what zones were invented for. The idea was that you could create a zone, and create one or more objects (and they might create any related objects) from that zone, and then you could destroy the zone and thereby destroy all the objects therein.
The problem is that that's rather incompatible with the notion of reference counting, i.e., ownerships. If you blow away a zone that contains one or more objects that something still owns (i.e., expects to still be able to use), things break. If all of those objects have been released by all of their owners by the time you destroy the zone, they have already been deallocated one at a time, so the zone accomplishes nothing and so was unnecessary.
Consequently, zones have been killed off, so while you might still prefer to do it the way you're doing it for stylistic consistency's sake, it won't make any significant difference in what happens at run time.