• 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: NSString initWithFormat and stringWith
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSString initWithFormat and stringWith


  • Subject: Re: NSString initWithFormat and stringWith
  • From: Erik Buck <email@hidden>
  • Date: Wed, 27 May 2009 11:05:18 -0400

Don't ever write either of the following lines:
> NSString *string1 = [NSString stringWithFormat:@"myFirstString"];
> NSString *string2 = [[NSString alloc] initWithFormat:@"mySecondString"];


the WithFormat methods parse the argument string. If your argument string contains any '%' characters those lines will likely crash.

Use NSString *string1 = [NSString stringWithString:@"myFirstString"];
or NSString *string2 = [[[NSString alloc] initWithString:@"mySecondString"] autorelease];


As I have written it above, you are not taking responsibility for later releasing either string1 or string2.

As an alternative, use
NSString *string1 = [[NSString stringWithString:@"myFirstString"] retain];
or NSString *string2 = [[NSString alloc] initWithString:@"mySecondString"];
or NSString *string3 = [@"myThirdString" copy];


In all of the alternate cases, you are taking responsibility for later releasing string1, string2, and string3.

As requested by the moderators for good reason and rather than misstate the simple memory management rules, I will just reference the official answer which is clear and precise and easy to follow: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

_______________________________________________

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: NSString initWithFormat and stringWith
      • From: Michael Ash <email@hidden>
  • Prev by Date: Re: Abstract class with single subclass
  • Next by Date: Re: Abstract class with single subclass
  • Previous by thread: Re: NSString initWithFormat and stringWith
  • Next by thread: Re: NSString initWithFormat and stringWith
  • Index(es):
    • Date
    • Thread