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

didSelectRowAtIndexPath display in UIWebView

ios parsing uitableview webview feed

I'm using MWFeedParser, and I want a tap on a cell to open up a webview rather than another UITableViewController. This is what happens at didSelect...

How to tell if a Targa is from Photoshop?

c++ photoshop file-format tga

I have run into an issue while trying to write a *.tga file reader. For 32 bit targas, photoshop fills the alpha channel with 255, which is still standard, and works, but in 16 bit targas, photoshop