views:

110

answers:

1

In the Xcode documentation for NSCopyObject, the special considerations section states:

This function is dangerous and very difficult to use correctly. It's use as part of copyWithZone: by any class that can be subclassed, is highly error prone. Under GC or when using Objective-C 2.0, the zone is completely ignored.

This function is likely to be deprecated after Mac OS X 10.6.

Why is it difficult to use correctly? It performs a shallow (bit-for-bit) copy. Objects are not copied or retained. The documentation is pretty clear on this.

If I'm not missing other reasons, what is the preferred alternative for performing a shallow copy of an object?

Edit:

There are valid reasons to want to perform a shallow copy. One example: a class may have many instance variables, most of which are primitive types (integer, float) or objects that are intentionally not retained to avoid retain cycles (delegates). A shallow copy using NSCopyObject copies all of these in one nice, self-documenting line of code. Any remaining ivars that do need to be reference counted can be retained or copied individually.

The alternative to this is to either assign to the new object using pointer syntax (newObject->ivar = ivar) or to create an init method with a potentially large number of arguments (one for each ivar to copy). The latter strikes me as especially ugly, but I suppose it doesn't need to be in the header and exposed to the world.

+1  A: 

You shouldn't make a shallow copy not involving the correct retain/release. Period.

Yuji
Obviously, but fixing those references is up to the developer. Your answer does not address my question of why `NSCopyObject` "is dangerous and very difficult to use correctly."
Steve Madsen