Re: literal strings - who do they belong to?
Re: literal strings - who do they belong to?
- Subject: Re: literal strings - who do they belong to?
- From: Peter N Lewis <email@hidden>
- Date: Mon, 13 Jul 2009 16:56:42 +0800
On 13/07/2009, at 13:55 , Wade Tregaskis wrote:
I know you guys probably know this, but to be technically accurate,
there is no guarantee the return value of stringByAppendingString
returns an autoreleased string.
While your point is true, it's not actually a rebuttal - you can
assume objects returned from such methods are autoreleased, because
that's the contract given.
No, that is not the contract.
The contract is you do not own them. The contract says nothing about
autoreleased.
<http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html
>
Whether they're cached or singletons or whatever else, they must
obey the policy that they'll stick around 'til the next flush of the
current thread's current autorelease pool. You just can't safely
handle the memory management otherwise, especially in multithreaded
cases.
This is exactly the misconception that needs to be avoided. Here is a
trivial counter example:
id obj = [dict objectForKey:@"whatever"];
[dict release];
NSLog( @"this will crash %@", id );
No autorelease pool, no remaining valid until the current autorelease
pool is flushed.
The contract says "You don't own it, don't release it" and "if you
want to keep it, retain/copy it".
Unfortunately, this contract isn't always followed. Lots of people
"optimise" away this policy instead of doing a "superfluous" 'return
[[foo retain] autorelease]'.
Read the rules, follow the rules.
It is not optimising away the return [[foo retain] autorelease], which
is explicitly allowed in the rules ("That method may also safely
return the object to its invoker"), it is assuming something about the
lifetime of the object you don't own that gets people in to trouble.
Enjoy,
Peter.
--
Clipboard Switching and Macros with Keyboard Maestro
Keyboard Maestro <http://www.keyboardmaestro.com/> Macros for your Mac
<http://www.stairways.com/> <http://download.stairways.com/>
_______________________________________________
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