views:

1421

answers:

1

Suppose I have a class like this:

@interface SomeClass : NSObject<NSCopying> {
    SomeOtherClass *obj;
}

In the definition of copyWithZone:, I do this:

SomeClass *someCopy = [[SomeClass allocWithZone:zone] init];

So my question is, if I want to make a copy of obj, which of these is correct/recommended?

option A:

objCopy = [obj copyWithZone:zone];

option B:

objCopy = [obj copy];
+1  A: 

If you are using reference-counted memory management (not Garbage Collection) you should use [obj copyWithZone:zone]. In addition, you should (in the same circumstances) use +allocWithZone: instead of +alloc to allocate the copies. This allocates memory for the instances in a specified memory zone (see NSZone). Developers might use a separate zone if they are going to allocate many objects which will be no longer needed at roughly the same time. The entire zone can then be reclaimed in one operation with NSRecylceZone, helping to prevent memory fragmentation. In general, using a private zone is not needed (and will generally hurt performance; profile your code!). Assuming the developer wants a copy in a particular zone, I think you would assume they would want all related instances in the same zone.

The -copy and +alloc methods call the -copyWithZone: and +allocWithZone: methods respectively, passing the default zone.

Barry Wark
Is there any particular reason--what's going on under the hood?
Sam Lee
A zone is an area from which you allocate memory. The idea is that you can make a whole bunch of related allocations (Cocoa objects, buffers, etc.) from one zone, then free the zone instead of all the objects in it. In practice, I hear, this doesn't really gain you much.
Peter Hosey