objective c – Understanding NSString comparison

objective c – Understanding NSString comparison

The reason why == works is because of pointer comparison. When you define a constant NSString using @, the compiler uniquifies the reference. When the same constants are defined in other places in your code, they will all point to the same actual location in memory.

When comparing NSString instances, you should use the isEqualToString: method:

NSString *myString1 = @foo;
NSString *myString2 = @foo;
NSString *myString3 = [[NSString alloc] initWithString:@foo];
NSLog(@%d, (myString2 == myString3))  //0
NSLog(@%d, (myString1 == myString2)); //1
NSLog(@%d, [myString1 isEqualToString:myString2]); //1
NSLog(@%d, [myString1 isEqualToString:myString3]); //1
[myString3 release];

Edit:

NSString *myString3 = [[NSString alloc] initWithString:@foo]; 
// this is same with @foo

initWithString: does not create a new reference any more, you will need initWithFormat,

NSString *myString3 = [[NSString alloc] initWithFormat:@foo];

The equality operator == only compares pointer addresses. When you create two identical strings using the literal @ syntax, the compiler will detect that they are equal, and only store the data once. Hence, the two pointers point to the same location. However, strings created by other means may contain identical data, yet be stored at different memory locations. Hence, you should always use isEqual: when comparing strings.

Note that isEqual: and isEqualToString: always return the same value, but isEqualToString: is faster.

objective c – Understanding NSString comparison

== compares locations in memory. ptr == ptr2 if they both point to the same memory location. This happens to work with string constants because the compiler happens to use one actual string for identical string constants. It wont work if you have variables with the same contents, because theyll point to different memory locations; use isEqualToString in such a case.

Leave a Reply

Your email address will not be published. Required fields are marked *