mengtuo zhu
mengtuo zhu

Reputation: 17

Why two strings allocated with NSString *str1 = [[NSString alloc]init]; have same address?

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?

Upvotes: 1

Views: 84

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726679

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.

Upvotes: 1

Related Questions