Reputation: 1065
Let's see a example:
Scenario 1:
NSString *str1=@"Hello";// str1 points to a literal string @"Hello"
NSString *str2=[[NSString alloc] initWithString:str1];
NSLog(@"%p %p",str1,str2);// str1 and str2 both point to same object
Scenario 2:
NSString *str3=[[NSString alloc] initWithFormat:@"Hello"];
NSString *str4=[[NSString alloc] initWithString:str3];
NSLog(@"%p %p",str3,str4);// str3 and str4 point to different objects
I want to know the difference between scenario 1 and 2.
Upvotes: 0
Views: 75
Reputation: 162722
It is an implementation detail (and indication that there is an optimization that Foundation could do that it isn't).
You should never assume that two objects are equal or unequal based on pointer equality. Pointer equality is only useful for checking if they are literally the same object. isEqual:
must be used to check if they are semantically identical.
Under the covers, Foundation knows that @"Hello"
is a constant string and creating a second immutable string from a constant string can just return the constant string.
It is assuming that initWithFormat:
will produce a non-constant string. The optimization opportunity is that Foundation could, during parsing of the format string, detect that no formatting was done and just return the constant string (I'm kinda surprised it doesn't-- I should file an bugenhancement request).
Upvotes: 1