1
NSString *str1 = [[NSString alloc]init];
NSString *str2 = [[NSString alloc]init];
NSLog(@"%p\n%p",str1,str2);

result

str1:0x7fff7b559d00
str2:0x7fff7b559d00

Why str1 and str2 have same memory address?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • It looks like Objective-C uses string pooling (just like Java). http://stackoverflow.com/questions/11556714/does-objective-c-use-string-pooling – Cheng-Yu Hsu Oct 25 '15 at 02:05

1 Answers1

1

NSString is immutable, so two empty strings are identical. Therefore, Cocoa can return the same object every time you create it.

The real question, however, how can this be done when alloc returns two different addresses for the two strings?

The answer is that init is allowed to substitute the value of self for anything it wishes, and return a completely different object. For example, NSString's init can be implemented like this:

-(id)init {
    static NSString *empty = nil;
    if (!empty) {
        empty = [[NSString alloc] initWithCharacters:"" length:0];
    }
    return empty;
}

Note: The real code in Cocoa will almost certainly be different; this is only an illustration to show how the same address could be returned for different allocations.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523