This discussion is archived
11732 Views 5 Replies Latest reply: Oct 20, 2008 4:07 AM by just.do.it
Currently Being ModeratedSep 1, 2008 10:57 PM (in response to wallclimber21)The difference is in how the return values are memory-managed. alloc/initWithFormat: returns a retained string that you will have to release or autorelease yourself. stringWithFormat: returns a string that has already been autoreleased. (An autoreleased object will be released when the current autorelease pool disappears; that usually happens right before the next event is processed.)
Which you should use depends on what you're doing with the string. If it's a temporary string, if it's going to be stored inside another object, or if it's going to be stored in your own object using the "self.property" syntax, use stringWithFormat:; if it's going to be assigned to a global, static or instance variable (without using "self.property"), use alloc/initWithFormat:.
In your case, you could go either way. stringWithFormat: would allow you to remove the explicit release call, but autoreleasing is also very slightly slower than releasing. It's up to you to decide whether you want your code to be smaller and simpler or longer and faster.MacBook, Mac OS X (10.5.4), iPhone EDGE 16GB
Currently Being ModeratedSep 1, 2008 10:57 PM (in response to wallclimber21)Perfect. That's more or less what I hoped it would be, but the doc's are not very specific about it.
Currently Being ModeratedSep 1, 2008 11:01 PM (in response to wallclimber21)The docs for NSString don't say this because it's a Cocoa-wide rule, and Apple doesn't want to explain the memory management rules in the documentation for every single method. :^) The rule is, if the method contains one of the words "new", "alloc", "retain", or "copy" (NARC), you have to release its return value yourself. If it doesn't--and this applies to all these sorts of shorthand constructors--then you don't have to release it yourself. That's always true everywhere in Cocoa, and you should try to make sure it's true in your code too. (So if you decide to use explicit releases, I'd suggest you add one of those words to your method name--maybe call it "newDictionaryKeyFromABC", for example.)MacBook, Mac OS X (10.5.4), iPhone EDGE 16GB
Currently Being ModeratedOct 19, 2008 11:57 PM (in response to Brent Royal-Gordon)Yes, but neither of these methods contain any of the NARC words. So the question remains how would you know this?20" Intel iMac, Mac OS X (10.4.6)
Currently Being ModeratedOct 20, 2008 4:07 AM (in response to rongreen)Yes, that's correct, but initWithFormat without an alloc in front does not make any sense. In fact it's the alloc message, which tell's us, the returned object is retained.MacBook Pro, Mac OS X (10.5.5)