4

I was just curious, is there any difference between the following two codes?

NSString *aString = [NSString stringWithString:@"a string"];

NSString *aString = @"a string";

I wonder what exactly is going on when you do the latter way.

bryanmac
  • 38,941
  • 11
  • 91
  • 99
Shinoj
  • 811
  • 2
  • 8
  • 18

1 Answers1

3

Both point to a literal string created at compile time.

Even though stringWithString suggest it's autoreleased, a literal string will never get released.

See my related post here:

Difference between NSString literals

From the apple docs @ https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html

Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated, though you can retain and release them as you do any other object.

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99
  • Hm... by following common rules `[NSString stringWithString:@"a string"]` should return autoreleased copy of "a string". Bryanmac, could you post a link that describes your answer? – brigadir Mar 06 '12 at 07:06
  • I guess it returns an autoreleased retained version of the literal `@a string"` that is passed in, but a link to some docs would help. –  Mar 06 '12 at 07:24
  • I added the link to the Creating Strings apple docs. It can't be released because it points to an offset in memory of the literal string compiled into the binary. See me related post that illustrates that. – bryanmac Mar 06 '12 at 07:55
  • BTW, it's not that it can't be released, it's just that the release has no effect. It's immune to ref counting essentially since it's literal and will always be around. – bryanmac Mar 06 '12 at 13:33