Both the following comparisons evaluate to true:
1)
@"foo" == @"foo";
2)
NSString *myString1 = @"foo";
NSString *myString2 = @"foo";
myString1 == myString2;
However, there are definitely times where two NSString
s cannot be compared using the equality operator, and [myString1 isEqualToString:myString2]
is required instead. Can someone shed some light on this?
==
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 won't work if you have variables with the same contents, because they'll point to different memory locations; useisEqualToString
in such a case.The reason why
==
works is because of pointer comparison. When you define a constantNSString
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 theisEqualToString:
method:Edit:
initWithString:
does not create a new reference any more, you will needinitWithFormat
,Check out this example:
So, the compiler is likely to use isEqualToString method to process isEquals for NSString's and dereference pointers, though it had not to. And the pointers are different, as you see.
An example demonstrating how address comparison as a surrogate for string comparison will break:
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 useisEqual:
when comparing strings.Note that
isEqual:
andisEqualToString:
always return the same value, butisEqualToString:
is faster.