I wonder if
return @"Text";
is autoreleased? And if it is so could you please explain it.
Is the compiler creating a NSString
object for us or how will the compiler handle this?
I wonder if
return @"Text";
is autoreleased? And if it is so could you please explain it.
Is the compiler creating a NSString
object for us or how will the compiler handle this?
Yes.
Anything that you do not alloc, retain, or copy should be treated as autoreleased.
No it's not.
@"Text"
is a constant string, that means the same object is returned every time that line runs and it gets never released.
- (void)release
is a no-op method. If you look at the class you see that it's not a normal NSString.
Constant NSStrings are compiled into the application binary. Releasing them is meaningless since the memory they use is readonly, does not come from the heap and cannot be recycled. If you look at the retain count of a constant NSString, you'll see it is set to some astronomically high number (2^31-1 I think). The convention is that -release
sent to an object with this retain count does nothing, neither does -retain
. Consequently, sending -autorelease
also does nothing except add the string to the autorelease pool (actually, even that might be optimised out).
In terms of ownership (which is how you should be thinking about this), treat constant NSStrings exactly like anything else. You don't obtain it using new, alloc, or copy, so unless you retain it, you don't own it. So you also don't need to autorelease it in your example before returning it.
The caller should retain the return value, if it wants to keep it, even though -retain
really does nothing. This makes your code more general, so if (for example) your method were changed to return a non constant NSString, you don't have to worry about changing all the callers.