Why Does String Not Equal What Is Stored?

别说谁变了你拦得住时间么 提交于 2019-12-31 07:32:19

问题


This is a simple, odd question...

if(tableViewNum == @"One") {
        if ([drinkArray objectAtIndex:0] == currentDate) {
            [updatedArray addObject:drinkArray];
            NSLog(@"MADE THE ELSE1");
        }
        NSLog(@"MADE THE ELSE2");
    }
    else if (tableViewNum == @"Two") {
        if ([[drinkArray objectAtIndex:0] isEqualToString:yesterdayDate])
            [updatedArray addObject:drinkArray];
    } else {
        NSLog(@"MADE THE ELSE %@",tableViewNum);
        [updatedArray addObject:drinkArray];
    }

In the very first if statement I ask if tableViewNum == @"One"

But I don't go in that section of the if statement even though tableViewNum actually does equal @"One"

As you can see the very last NSLog all ways comes out as

MADE THE ELSE One

But if tableViewNum really equaled One it would have gone through the if statement not the else statement code...?????


回答1:


You can't compare strings with the == operator. Use isEqualToString instead:

if([tableViewNum isEqualToString:@"One"]) {
    // etc.

… and the same for the rest of the conditions. You're already doing it right in the second block.




回答2:


To be more specific, you shouldn't compare ANY objects using ==. This compares just the pointers. Use [obj isEqual: otherObj] or with NSStrings isEqualToString: as described above.



来源:https://stackoverflow.com/questions/11348809/why-does-string-not-equal-what-is-stored

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