问题
Possible Duplicate:
Understanding NSString comparison in Objective-C
I'v encountered strange things in objective-c, I'm trying to compare cell.label with elements title which is string. to identify whever it is a cell I am looking for.
NSLog(@"%@", cell.textLabel.text);
NSLog(@"%@", [_dropDownSelection1.elements[1] title]);
if(cell.textLabel.text == [_dropDownSelection1.elements[1] title]){
NSLog(@"Positive");
}
else{
NSLog(@"Negative");
}
NSLog prints that the text in both is exactly the same, but still i always end up with negative... Why is that?
回答1:
You should use [cell.textLabel.text isEqualToString:[_dropDownSelection1.elements[1] title]] to compare the strings.
回答2:
You are comparing pointers with one another, not the strings.
Use IsEqual instead.
回答3:
You can't compare them like that.
See the section Identifying and comparing strings on the Objective-C docs.
回答4:
Here is the code which worked for me! I don't know why but, without initializing variables i couldn't get it work, even using isEqualToString as provided above.
NSLog(@"CELL:%@", cell.textLabel.text);
NSLog(@"ELEM:%@", [_dropDownSelection1.elements[1] title]);
NSString *labl = cell.textLabel.text;
NSString *tit = [_dropDownSelection1.elements[1] title];
if([labl isEqualToString:tit])
{
NSLog(@"Positive");
}
else{
NSLog(@"Negative");
}
回答5:
Method for compare two strings is isEqualToString:
Your code is like this
NSLog(@"%@", cell.textLabel.text);
NSLog(@"%@", [_dropDownSelection1.elements[1] title]);
if(cell.textLabel.text isEqualToString:[_dropDownSelection1.elements[1] title])
{
NSLog(@"Positive");
}
else
{
NSLog(@"Negative");
}
来源:https://stackoverflow.com/questions/13082427/equal-strings-not-equal