• 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: Inconsistent Memory Management Rules
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Inconsistent Memory Management Rules


  • Subject: Re: Inconsistent Memory Management Rules
  • From: Sherm Pendley <email@hidden>
  • Date: Mon, 14 Apr 2003 00:14:09 -0400

On Sunday, April 13, 2003, at 02:54 PM, David Blanton wrote:

NSString * string = [[NSString alloc]init];

The variable "string" now points to an instance of NSString that was created by alloc, and therefore needs to be released.

string = [string stringByAppendingString:@"steve jobs"];

"string" now points to a *new* instance of NSString - one that was not created with -alloc or -copy, and is therefore already autoreleased.

You haven't called -release or -autorelease on the original NSString instance, so that instance leaks.

[string release]; // always crashes

This crashes because you're calling -release on an object that has already been -autoreleased. The variable "string" points to the object created by the call to -stringByAppendingString, which is not the same object that you originally created with +alloc.

Can someone explain this inconsistency?

No inconsistency, just a minor misunderstanding. It looks like what you want to do is append a string to an existing string, without creating a new string. To do that, the original needs to be mutable, like this:

NSMutableString *string = [[NSString alloc] init];
[string appendString: @"Steve Jobs"];

It may help to know that Cocoa method names follow fairly consistent patterns. Whenever you see a method with a name like "fooByBar:", it's usually - always, as far as I know - safe to assume that what that method returns is a new autoreleased object, not a reference to the object that received the message.

sherm--

Heisenberg may have slept here.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

References: 
 >Inconsistent Memory Management Rules (From: David Blanton <email@hidden>)

  • Prev by Date: Re: Inconsistent Memory Management Rules
  • Next by Date: Re: Inconsistent Memory Management Rules
  • Previous by thread: Re: Inconsistent Memory Management Rules
  • Next by thread: Re: Inconsistent Memory Management Rules
  • Index(es):
    • Date
    • Thread