Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class with an accessible method that passes back an NSString when called.

[MyClass getMyString]

The string variable in that class is actually assigned in the didSelectRowAtIndexPath: part of a table like this:

myString = cell.textLabel.text;

When I retrieve the string by calling that method, I assign it to another string in the class that called it and compare it to a string I have defined

NSString *mySecondString;
mySecondString = @"my value";

if(mySecondString == myString){
    i = 9;
}

I have stepped through the code and every time it evaluates the if statement, it skips right past the i=9 and goes to the next else if statement. Why would this be? Why don't they evaluate to be the same value? If you hover your cursor over each of the values during debugging they will show they have the same value, but the code for some reason with not do as I expect it to do and assign 9 to i.

Any thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
419 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're assuming that the C == operator does string equality. It doesn't. It does pointer equality (when called on pointers). If you want to do a real string equality test you need to use the -isEqual: method (or the specialization -isEqualToString: when you know both objects are strings):

if ([mySecondString isEqualToString:myString]) {
    i = 9;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...