Re: Autorelease Question
Re: Autorelease Question
- Subject: Re: Autorelease Question
- From: Andy Lee <email@hidden>
- Date: Wed, 19 Nov 2008 18:53:42 -0500
On Nov 19, 2008, at 5:37 PM, Carmen Cerino Jr. wrote:
I am not sure the best way to phrase this question into words, so I
will phrase it using example code.
- (NSString*)foo
{
NSString blah = [NSString string];
.........
//Now do I do:
return blah;
//Or:
return [[blah retain] autorelease]];
}
Both return statements are consistent with the memory management
rules, but in this particular example, the retain and autorelease are
superfluous.
I wonder if you're asking because you've seen accessor methods that
use the second variation? For example, if you have a Person class
with a "name" ivar:
- (NSString *)name
{
return [[name retain] autorelease];
}
In this case an argument can be made for the retain and autorelease as
opposed to just "return name;". They protect from something like this:
Person *aPerson = [[Person alloc] init];
// ... some code which sets the person's name along the way ...
NSString *aName = [aPerson name];
[aPerson release];
The [aPerson release] might cause aPerson to be deallocated, which
might cause its name to be deallocated, which would cause aName to be
a bad pointer.
When I saw this pitfall, I panicked and thought I'd need to rewrite
all my getter methods. But it was Jens Ayton, I think, who noted that
in practice one is very unlikely to run into this pitfall, so really
it's a matter of personal preference.
_______________________________________________
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