• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Autorelease Question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Follow-Ups:
    • Re: Autorelease Question
      • From: "Carmen Cerino Jr." <email@hidden>
References: 
 >Autorelease Question (From: "Carmen Cerino Jr." <email@hidden>)

  • Prev by Date: Re: Blue default button style hangs.
  • Next by Date: Re: Autorelease Question
  • Previous by thread: Re: Autorelease Question
  • Next by thread: Re: Autorelease Question
  • Index(es):
    • Date
    • Thread