Re: copy vs mutableCopy?
Re: copy vs mutableCopy?
- Subject: Re: copy vs mutableCopy?
- From: Rob Ross <email@hidden>
- Date: Tue, 11 Jul 2006 09:07:35 -0700
On Jul 11, 2006, at 8:50 AM, Greg Titus wrote:
On Jul 11, 2006, at 8:50 AM, Rob Ross wrote:
Ok, I know the difference between a mutable and immutable object.
And I know the difference between a shallow copy and a deep copy.
But I am having trouble understanding the difference between
implementing copy vs mutable copy, since it seems you can make
mutable copies of immutable objects, and immutable copies of
mutable objects. I'm just a bit confused how this works in practice.
I've read this:
http://developer.apple.com/documentation/Cocoa/Conceptual/
MemoryMgmt/Tasks/ImplementCopy.html
but it doesn't really tell me the difference between the two methods.
The difference is in the intent of the caller. You make a
mutableCopy when you want to make a copy that you can later modify
for yourself, and make a copy when you want to make a copy to hold
onto unchanged.
For many objects, the implementation of the two methods can be
identical. But knowing the intent of the caller allows certain
optimizations, such as returning the same immutable object (just
retained again) from a call to -copy, because you know that the
caller just wants something to hold onto unchanged, and the
existing object can not change.
Hope this helps,
- Greg
Yes, this does help.
As a followup, say I have an object with one instance variable, an
NSMutableString. And say some code calls -copy on this object. You're
saying that the intent is for an immutable copy? So I just retain the
ivar and copy the reference to a new object and return that instance,
even though the ivar is itself mutable? As the implementor of the -
copy method, I am trusting that the client will not make changes to
this value since it would affect another instance? Is this correct?
And similarly, if -mutableCopy is called, I would make a deep copy of
the NSMutableString, even though it's already mutable, because the
intent of the caller is to modify that value and I don't want the
original object mutated? Is this also correct?
Thanks for the help!
Rob
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden