Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 513
Coocoo4Cocoa Avatar asked Dec 01 '08 03:12

Coocoo4Cocoa


2 Answers

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).

like image 124
Ben Gottlieb Avatar answered Oct 13 '22 22:10

Ben Gottlieb


As mentioned in the docs

http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html

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.

like image 20
August Avatar answered Oct 13 '22 22:10

August