Difference between NSString literals

@”My String” is a literal string compiled into the binary. When loaded, it has a place in memory. The first line declares a variable that points to that point in memory.

From the string programming guide:

The simplest way to create a string object in source code is to use
the Objective-C @”…” construct:

NSString *temp = @"/tmp/scratch"; 

Note that, when creating a string
constant in this fashion, you should avoid using anything but 7-bit
ASCII characters. 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.

The second line allocates a string by taking that literal string. Note that both @”My String” literal strings are the same. To prove this:

NSString *str = @"My String";
NSLog(@"%@ (%p)", str, str);

NSString *str2 = [[NSString alloc] initWithString:@"My String"];
NSLog(@"%@ (%p)", str2, str2);

NSString *copy = [str2 stringByAppendingString:@"2"];
NSLog(@"%@ (%p)", copy, copy);

Outputs the same memory address:

2011-11-07 07:11:26.172 Craplet[5433:707] My String (0x100002268)
2011-11-07 07:11:26.174 Craplet[5433:707] My String (0x100002268)
2011-11-07 07:11:26.174 Craplet[5433:707] My String2 (0x1003002a0)

What’s telling is not only are the first two string the same memory address, but if you don’t change the code, it’s the same memory address every time you run it. It’s the same binary offset in memory. But, not only is the copy different but it’s different every time you run it since it’s allocated on the heap.

The autorelease has no affect according to the doc ref above. You can release them but they are never deallocated. So, they are equal not because both are autoreleased string but that they’re both constants and the release is ignored.

Leave a Comment