iPhone - 将 nil NSString 与另一个有价值的 NSString 进行比较返回 NSOrderedSame

发布于 2024-10-27 04:06:02 字数 441 浏览 8 评论 0原文

我正在用另一个字符串测试一个字符串,我注意到如果第一个字符串为零,则返回值等于 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 test
if(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

贱贱哒 2024-11-03 04:06:02

您可以尝试

[someString isEqualToString:@"someOtherString"];

Or 不区分大小写:

[[someString lowerCaseString] isEqualToString:[otherString lowerCaseString]];

You can try

[someString isEqualToString:@"someOtherString"];

Or for case insensitive:

[[someString lowerCaseString] isEqualToString:[otherString lowerCaseString]];
朕就是辣么酷 2024-11-03 04:06:02

我会使用 @seretur 建议的方法,除非你担心情况。在这种情况下,我将使用 caseInsensitiveCompare: ,它类似于您当前使用的 compare: 方法。

您还可以像这样简化 if 语句:

if (oneString && [oneString caseInsensitiveCompare:otherString] == NSOrderedSame) { ...

I would use the approach @seretur suggests unless you are worried about case. In that case, I'd use caseInsensitiveCompare: which is similar to the compare: method you are currently using.

You can also simplify that if statement like so:

if (oneString && [oneString caseInsensitiveCompare:otherString] == NSOrderedSame) { ...
青朷 2024-11-03 04:06:02

According to the documentation, the string must not be nil. If it is, it can result in quirky behavior.

呆头 2024-11-03 04:06:02

向 nitl 发送东西是绝对合法的。但根据定义它总是返回 nil。而nil本身实际上是0

如果我们 现在看看NSComparisonResultNSOrderedSame也是0。

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;

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.

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文