Releasing of strings
I got a doubt that when should the st开发者_JAVA技巧rings are released.I am not made any allocation to the string is there any necessary to release the string?
No if you do not "allocate" the string they are auto released. for example
NSString *aTestString = [NSString stringWithFormat:@"Hello %@",@"World"];
This string is auto released, so you do not have to call [aTestString release];
If you would do:
NSString *aTestString = [[NSString alloc] initWithFormat:@"Hello %@",@"World"];
Then you would need to release it by [aTestString release]; because you manually allocated. Therefore it is wise to autorelease it, so you do not have to think of it later on
NSString *aTestString = [[[NSString alloc] initWithFormat:@"Hello %@",@"World"] autorelease];
But that would just be the same as the first piece of code I gave ya. Back to the point, no you do not have to manually release it as long as you do not allocate it yourself.
Did you create the string via a call to alloc
, new
, or a method containing copy
? Did you explicitly retain
the string yourself? If you got the NSString
from a CFStringRef
, did you create the CFStringRef
with a function that included create
? If not, you don't have to do anything. If you did, you have to either release
or autorelease
the string.
Object allocation/deallocation rules
You need to call [Object release]
if and only if:
- You called
[Object alloc]
- You called
[Object retain]
- You called
[Object new]
If you did not explicitly allocate or retain the object, then you need to release it. If you got the object via a class method, the method did something like this: return [[[Object alloc] init] autorelease];
. This allocates a new object, but is autoreleased when the NSAutoReleasePool next gets a chance.
精彩评论