Equal strings not equal? [duplicate]

北战南征 提交于 2019-12-12 06:24:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!