NSString compare:和isEqual(ToString):之间有区别吗? [英] Is there a difference between NSString compare: and isEqual(ToString):?

查看:113
本文介绍了NSString compare:和isEqual(ToString):之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会找到代码来测试两个NSString是否相同:

Occasionally I find code which tests if two NSStrings are the same like this:

if ([str1 compare:str2] == NSOrderedSame) {
    // Do something
}

现在,我认为这比使用isEqualToString:更具可读性,并且还具有一些令人讨厌的副作用,例如,如果str1 == nil if(..)的计算结果为true,或者何时str2 == nil破坏可能对我们造成破坏根据Apple文档. (编辑:正如hatfinch指出的那样,如果str1 == nil && str2 == nil两种变体都产生错误的结果.因此无论如何,您都需要保护自己免受这种情况的伤害.)

Now, I believe this is less readable than using isEqualToString: and it also has some nasty side effects, like if str1 == nil the if(..) evaluates to true, or when str2 == nil havoc might break upon us according to the Apple docs. (Edit: As hatfinch points out, if str1 == nil && str2 == nil both variants produce the wrong result. So you need to guard yourself against this case anyway).

但是在我努力反对公司代码中的那些声明之前,我想确保自己不会错过一些重要的观点.

But before I crusade against those statements in my companys code, I wanted to make sure I didn't miss some important point.

所以我的问题基本上可以归结为:compare:NSOrderedSameisEqual:之间有什么区别吗?

So my question basically boils down to: Is there any difference between a compare: to NSOrderedSame and isEqual:?

推荐答案

阅读文档,我发现您尚未提到的唯一区别是:

Reading the docs, the only differences I can find that you haven't already mentioned are:

  1. isEqualToString:首先比较两个字符串的id,这是频繁使用字符串的应用程序中潜在的速度增益.从NSString参考:

  1. isEqualToString: first compares the id of the two strings, which is a potential speed gain in an application that makes frequent re-use of strings. From the NSString reference:

返回值:
如果aString等于接收者(如果它们具有相同的id或在文字比较中它们是否为NSOrderedSame),则为YES,否则为否.

Return Value:
YES if aString is equivalent to the receiver (if they have the same id or if they are NSOrderedSame in a literal comparison), otherwise NO.

如上引言所示,

  • isEqualToString:确实与compare: options:NSLiteralSearch更相似. NSLiteralSearch对Unicode字符表示更为挑剔:

  • isEqualToString: is really more analogous to compare: options:NSLiteralSearch, as can be seen in the above quote. NSLiteralSearch is more finicky about Unicode character representation:

    文字"在应用于字符串比较时表示不应用各种Unicode分解规则,并且分别比较Unicode字符.因此,例如,由组合字符序列"O"和变音符号表示的Ö"将不等于表示为一个Unicode字符的Ö".

    "Literal" when applied to string comparison means that various Unicode decomposition rules are not applied and Unicode characters are individually compared. So, for instance, "Ö" represented as the composed character sequence "O" and umlaut would not compare equal to "Ö" represented as one Unicode character.

  • 与您的问题中提到的误报和未定义的行为相比,这真是挑剔.

    This is really just nitpicking compared with the false positives and undefined behavior mentioned in your question.

    来源: 查看全文

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