Is a literal NSString autoreleased or does it need to be released?

When creating a string using the following notation:

NSString *foo = @"Bar";

Does one need to release foo? Or is foo autoreleased in this case?


Compiler allocated strings (of the format @"STRING") are constant, and so -retain, -release, and -autorelease messages to them are ignored. You don't have to release or autorelease foo in this case (but it won't hurt).

As mentioned in the docs

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.

Since you're not using alloc, copy, etc. you don't need to worry about releasing the object.

I agree with @Ben\ Gottlieb at "Compiler allocated strings (of the format @"STRING") are constants" but as you have not initialized them via passing an alloc or retain message, you must not pass release or autorelease message to them otherwise your app will crash with the following log

"pointer being freed was not allocated"


NSString *str = [NSString string];

is equivalent to:

NSString *str = [[[NSString alloc] init] autorelease];

so release or autorelease must not be passed here too.

Need Your Help

How to find the best matching key in a PHP array

php arrays

I have an associative array in php. the keys are integers. how do i find the nearest key to any integer input?