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