On 13/02/2012, at 11:44 AM, James Maxwell wrote:

> Okay, just saw an interesting post on this:
> 
> http://stackoverflow.com/questions/1459598/how-to-copy-an-object-in-objective-c
> 
> This is quite different from what I've generally seen, which just does:
> 
> MyClass* copy = [[self class] allocWithZone:zone];
> 
> then uses accessors to assign all the properties, and returns the copy.
> 
> But does that just give me a shallow copy?  Do I really have to implement the 
> version in the post -- that is, do I have to "call copyWithZone on all of 
> [my] fields" to get a true, mutable copy, that doesn't muck with the 
> original? I guess it makes sense, but I'm kind of surprised that the normal 
> copy (i.e., the one I see everywhere) doesn't do that already, since that's 
> what a "copy" seems to be, in the most general sense. (If I "copy" a paper 
> document, I can burn the copy, write all over it, or whatever I want, without 
> touching the original.)



It depends on what your properties are. You don't say.

If they are objects, then the copy doesn't copy those objects, but only their 
pointers, and so if you change the value of any of those objects, your copy 
gets changed as well.

You can avoid that by making the property setter copy the object, so that a 
simple assignment also performs a copy, then your -copyWithZone: method can use 
the accessors and will get a "deep" copy. But if your property is defined as 
assign or retain, then it will only perform a shallow copy.



Personally I've found reimplementing -isEqual and -hash quite tricky if you 
have to compute that yourself. Where possible, defer to the objects that you 
have as properties, so in other words, your outer -isEqual can simply call the 
-isEqual methods of the contained properties and AND them together. You may not 
need to supply a -hash method if you always perform deep copies, but again, you 
might be able to defer to the internals - for example by returning the XOR of 
the hashes returned by the properties.

--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to