I have 2 string, say textfield.text and [textArray objectAtIndex:i] They contain the same string (and tested by NSLog).
//this returns a false
if (textfield.text == [textArray objectAtIndex:i])
//this returns a true
[textArray replaceObjectA开发者_JS百科tIndex:i withObject:textfield.text];
if (textfield.text == [textArray objectAtIndex:i])
//this is also true
if ([textfield.text isEqualToString:[textArray objectAtIndex:i]])
Why is the first one returning a false?
When you use an == on pointers like NSString * it is comparing memory addresses, not comparing the value of strings.
Your first example:
if (textfield.text == [textArray objectAtIndex:i])
Is comparing two different memory address. Since they are not the same memory address, the answer is false
.
Your second example:
[textArray replaceObjectAtIndex:i withObject:textfield.text];
if (textfield.text == [textArray objectAtIndex:i])
Here you have assigned the memory address of textfield.text
into [textArray objectAtIndex:i]
thus making them the same memory address. Therefore, the memory addresses are the same so the result is true
.
Your last example:
if ([textfield.text isEqualToString:[textArray objectAtIndex:i]])
Is the correct way to evaluate two strings regardless of memory addresses because isEqualToString
compares the value of the strings and not their memory addresses.
Hope this helps.
The ==
operator tests if both references point to the same object, not if the strings are equal. Use isEqualToString:
if you want to compare the string contents.
if (textfield.text == [textArray objectAtIndex:i])
is an equality (not logical equality sorry). You can't use that for strings.
if ([textfield.text isEqualToString:[textArray objectAtIndex:i]])
However isEqualToString is the equivalent of the statement above. Specifically for strings.
In the first example, have you added the object to the array yet??
As a side note, you cannot compare your NSStrings
with ==
. You should use isEqualToString:
for that.
精彩评论