Re: Objective-C basics - (Why NSNumber conforms to NSCopying protocol)
Re: Objective-C basics - (Why NSNumber conforms to NSCopying protocol)
- Subject: Re: Objective-C basics - (Why NSNumber conforms to NSCopying protocol)
- From: Britt Durbrow <email@hidden>
- Date: Thu, 11 Aug 2016 01:50:41 -0700
> On Aug 11, 2016, at 12:04 AM, Quincey Morris <email@hidden> wrote:
>
> 2. The fact than an object is immutable does not (in general) mean that a copy can be represented by the same object reference. For example, an object that contained its own date of creation might be immutable, but a copy might have a different date, and therefore be a different object. Putting this another way, the immutability does not make NSCopying conformance irrelevant.
Hmm… I’m not so sure that this is *quite* right… what if I want a copy of the original object, with the same creation date? Not doing so could lead to some strange pitfalls, depending on what is then done with the alleged “copy”, and how it reacts to other methods (like -hash and -isEqual, or any sort of serialization methods it implements).
From the documentation:
"The exact meaning of “copy” can vary from class to class, but a copy must be a functionally independent object with values ___identical___ to the original at the time the copy was made.” (emphasis mine)
Which, IMHO, means that *all* the values stored in the object must be the same.
By extension; [anObject hash] and [[anObject copy] hash] must return the same value; and [anObject isEqual:[anObject copy]] must return YES.
For the case of an immutable object, those conditions are indeed fulfilled by simply returning self; because by definition an immutable object and a copy of an immutable object at a different memory address would behave the same, forever. Returning self is, in this case, just an implementation detail (an optimization, specifically).
It is, however, perfectly valid (if not encouraged for performance and memory use reasons) to actually create a new object, with all the same values as the original.
At a higher level, instead of having -copy return an object that was *almost* a copy; I think I would (if possible) refactor the problem to put that information somewhere else… or better yet, don’t do that at all (and given that copies come and go; I don’t think that non-invariant metadata like that is going to do what is usually desired, in the broader sense of solving the problem at hand; whatever problem it may be).
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden