Re: Memory Management question
Re: Memory Management question
- Subject: Re: Memory Management question
- From: j o a r <email@hidden>
- Date: Fri, 26 Dec 2008 10:14:46 -0800
On Dec 26, 2008, at 9:28 AM, Michael Ash wrote:
But yes, generally,
you should retain any object that's being passed into a method to
ensure
that it stays around for the lifetime of that method and release
them when
you exit.
Absolutely false. Never do this. If you find yourself doing this then
it means you've either horribly misunderstood something or you've
encountered a severe bug. The correct course of action is to either
correct the misunderstanding or correct the bug, not to wrap all of
your methods in retain/release calls.
While I agree with your recommendation to not retain all local
parameters and variables, there is something to be said for doing so.
It's not difficult to argue that it is more correct from a conceptual
point of view, and the reason to omit this ownership swizzle is
primarily that it's for the most part redundant.
The reason why this can be useful is easy to see:
{
id foo = [self foo]; // A local variable or parameter
[self bar]; // Can lead to deallocation of "foo" as a side effect
NSLog(@"Foo: %@", foo); // Trying to use "foo" here can lead to crash
}
Whenever you call "out" from the local scope, you can't in the general
case know that your non-retained variables will survive. You might
think that you know, if you control all of the code that you call to,
but it's not difficult to introduce regressions later on.
This is also why the recommended Cocoa implementation of a getter
accessor method returns an object like this:
return [[obj retain] autorelease];
I'm not a fan of this recommendation, and it's sort of in competition
with the recommendation made in this thread. If I had to choose, I'd
rather see explicit retains and releases in the local scope, than this
type of "hack" in the getter methods (I think that the decision should
be made in the receiver). I typically choose to do neither though! :-)
Two final notes:
* This is really a very, very, small problem in practice. I think that
over my ~8 years of full time Cocoa programming, I've only had to
troubleshoot such a problem once or twice in real world code.
* This discussion only applies to RR (retain/release) code, in GC
(garbage collection) you get this "safer" behavior "for free", since
the pointers you have to local variables on the stack will prevent
deallocation.
j o a r
_______________________________________________
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