21

When creating a string using the following notation:

NSString *foo = @"Bar";

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

jscs
  • 63,694
  • 13
  • 151
  • 195
Coocoo4Cocoa
  • 48,756
  • 50
  • 150
  • 175

3 Answers3

18

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

Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
15

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.

August
  • 12,139
  • 3
  • 29
  • 30
  • Anything changes after ARC? I read string literals stays in memory and gets destroyed when program stops running. One should prefer creating strings using alloc over literals? – rohan-patel Oct 14 '14 at 16:49
7

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"

NOTE

NSString *str = [NSString string];

is equivalent to:

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

so release or autorelease must not be passed here too.

Community
  • 1
  • 1
Madhup Singh Yadav
  • 8,110
  • 7
  • 51
  • 84