gpt4 book ai didi

objective-c - NSString比较: and isEqual(ToString):?有区别吗

转载 作者:太空狗 更新时间:2023-10-30 03:36:21 25 4
gpt4 key购买 nike

偶尔我会找到测试两个 NSString 是否相同的代码,如下所示:

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

现在,我认为这比使用 isEqualToString: 可读性差,而且它还有一些讨厌的副作用,比如 if str1 == nil if(..)根据 Apple 文档,计算结果为 true,或者当 str2 == nil 破坏可能对我们造成破坏时。 (编辑:正如 hatfinch 指出的那样,如果 str1 == nil && str2 == nil 两种变体都会产生错误的结果。因此无论如何您都需要防范这种情况) .

但在我反对我公司代码中的这些语句之前,我想确保我没有遗漏一些重要的点。

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

最佳答案

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

  1. isEqualToString: 首先比较两个字符串的 id,这对于频繁重复使用字符串的应用程序来说是一个潜在的速度增益。来自 NSString 引用:

    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.

  2. isEqualToString: 实际上更类似于 compare: options:NSLiteralSearch,如上面的引用所示。 NSLiteralSearch 对 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.

与您问题中提到的误报和未定义行为相比,这实际上只是吹毛求疵。

来源:NSString Class Reference

关于objective-c - NSString比较: and isEqual(ToString):?有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2877418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com