如果“a == b”在比较两个NSString对象时为false [英] If "a == b" is false when comparing two NSString objects

查看:111
本文介绍了如果“a == b”在比较两个NSString对象时为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有一个可访问的方法,传递回 NSString 时调用。

  [MyClass getMyString] 

该类中的字符串变量实际上是在 didSelectRowAtIndexPath:部分中分配的,如下所示:

  myString = cell.textLabel.text; 

当我通过调用该方法检索字符串时,我将它分配给另一个字符串,它与我定义的字符串比较

  NSString * mySecondString; 
mySecondString = @my value;

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



我已经遍历了代码,每次评估if语句跳过 i = 9 ,然后转到下一个 else if 语句。为什么会这样?为什么他们不评价为相同的值?如果在调试期间将光标悬停在每个值上,它们将显示它们具有相同的值,但是代码因为某种原因没有按我的预期做,并分配 9

>解决方案

您假设C == 运算符确实是字符串相等。它不。它的指针相等(当在指针上调用时)。如果你想做一个真正的字符串相等测试,你需要使用 -isEqual:方法(或专业化 -isEqualToString:

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


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?

解决方案

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;
}

这篇关于如果“a == b”在比较两个NSString对象时为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆