Re: Cocoa-dev Digest, Vol 5, Issue 2186
Re: Cocoa-dev Digest, Vol 5, Issue 2186
- Subject: Re: Cocoa-dev Digest, Vol 5, Issue 2186
- From: Steve Wetzel <email@hidden>
- Date: Sun, 21 Dec 2008 10:21:27 -0600
You're very confused. When you assign something new to myObj, you're
only affecting that one pointer. You don't affect anything else that
has a reference to the original object. For example:
NSString *str = @"hello";
[stack push:str];
str = @"world";
[stack push:str];
Your stack now contains @"hello" and @"world". It does not matter what
its copying behavior is, this is *always* true. (Try it with an
NSMutableArray and see; NSMutableArray does not copy the objects it
receives.) When you write str = @"world" you just put a new address
into the str pointer. But the stack isn't holding your str variable.
It's simply holding the value that str held originally. So there's no
problem.
What copying saves you from is stuff like this:
NSMutableString *str = [NSMutableString stringWithString:@"hello"];
[stack push:str];
[str setString:@"world"];
[stack push:str];
In this case the stack ends up holding two copies of a single mutable
string which contains the text @"world". Here we aren't mutating
"str", we're mutating the *object* that it points to. If the stack
copied the object then we wouldn't mutate the copy and so the
-setString: call wouldn't change its contents.
This usually isn't much of a problem. And to the extent that it is,
being able to push non-copyable objects or referenced mutable objects
onto a stack will generally far outweigh them. Follow Cocoa's lead:
with the exception of dictionary keys, Cocoa does not copy objects
that are put into collections.
Mike
Thanks Mike, I thought about it a long time before posting, then
posted, then when going to bed realize the first part of what you
said. I don't need to create separate instances to push 100 objects
onto the stack.
Thanks for posting the stuff about [str setString:@"world"], That
helped clarify this in my mind.
NOW I am trying to get my head around memory management with my little
stack. If anyone has insights and wants to share them feel free.
Instead of posting a question I think I will load up my little app,
look at retain counts, and try to figure out how to stop all my memory
leaks.
Steve
_______________________________________________
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