0

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?

Community
  • 1
  • 1
Datenshi
  • 1,191
  • 5
  • 18
  • 56
  • 1
    try using this format `[foo isEqualToString:bar]` for string comparison since yu are comparing the text itself – Jon Taylor Oct 26 '12 at 07:16

5 Answers5

3

You should use [cell.textLabel.text isEqualToString:[_dropDownSelection1.elements[1] title]] to compare the strings.

lqs
  • 1,434
  • 11
  • 20
3

You are comparing pointers with one another, not the strings.

Use IsEqual instead.

AndersK
  • 35,813
  • 6
  • 60
  • 86
1

You can't compare them like that.

See the section Identifying and comparing strings on the Objective-C docs.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Rik
  • 3,328
  • 1
  • 20
  • 23
0

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");

}
Datenshi
  • 1,191
  • 5
  • 18
  • 56
0

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");
}
Rahul Patel
  • 5,858
  • 6
  • 46
  • 72
Arvind Kanjariya
  • 2,089
  • 1
  • 18
  • 23