iPhone - 将 nil NSString 与另一个有价值的 NSString 进行比较返回 NSOrderedSame
我正在用另一个字符串测试一个字符串,我注意到如果第一个字符串为零,则返回值等于 NSOrderedSame (值为 0)。
if([oneString Compare:otherString] == NSOrderedSame)
如果 oneString 为零,则返回 YES。
所以我应该测试 if(oneString != nil && [oneString Compare:otherString] == NSOrderedSame)
我想我还应该在条件下测试 otherString,如果我想要的话,可以做一个特殊的情况 [nil Compare:nil]
返回 NSOrderedSame
。
是否有更方便的方法来比较字符串而无需进行此类测试并真正测试两个字符串是否相同?
I'm testing a string with an other, and I notice that if the first string is nil, the return value equals NSOrderedSame (valued to 0).
if([oneString compare:otherString] == NSOrderedSame)
returns YES if oneString is nil.
So I should testif(oneString != nil && [oneString compare:otherString] == NSOrderedSame)
I guess I should also test otherString in the condition, and make a special case if I want that [nil compare:nil]
returns NSOrderedSame
.
Is there a more convenient way to compare string without having to do such tests and to really test if both strings are the same ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试
Or 不区分大小写:
You can try
Or for case insensitive:
我会使用 @seretur 建议的方法,除非你担心情况。在这种情况下,我将使用
caseInsensitiveCompare:
,它类似于您当前使用的compare:
方法。您还可以像这样简化 if 语句:
I would use the approach @seretur suggests unless you are worried about case. In that case, I'd use
caseInsensitiveCompare:
which is similar to thecompare:
method you are currently using.You can also simplify that if statement like so:
根据文档,字符串不能为 nil。如果是这样,可能会导致奇怪的行为。
According to the documentation, the string must not be nil. If it is, it can result in quirky behavior.
向 nitl 发送东西是绝对合法的。但根据定义它总是返回 nil。而nil本身实际上是0。
如果我们 现在看看
NSComparisonResult
,NSOrderedSame
也是0。It is absolute legal to send something to nitl. But by definition it will always return nil. and nil itself actually is 0.
If we now look at
NSComparisonResult
,NSOrderedSame
is 0 too.