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

问题描述

我有一个具有可访问方法的类,该方法在调用时传回 NSString.

I have a class with an accessible method that passes back an NSString when called.

[MyClass getMyString]

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

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

我已经遍历了代码,每次它评估 if 语句时,它都会跳过 i=9 并转到下一个 else if 语句.为什么会这样?为什么它们不评估为相同的值?如果您在调试期间将光标悬停在每个值上,它们将显示它们具有相同的值,但是由于某种原因,代码没有按照我的预期执行并将 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.

有什么想法吗?

推荐答案

您假设 C == 运算符执行字符串相等.它没有.它执行指针相等(当调用指针时).如果您想进行真正的字符串相等性测试,您需要使用 -isEqual: 方法(或者当您知道两个对象都是字符串时,使用特化 -isEqualToString: 方法):

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:53