Re: NSString initWithFormat and stringWith
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