Objective-C中的字符串比较

106

我目前有一个 web 服务器,用于与我的 iPhone 应用程序通过 SOAP 进行通信。我返回一个包含 GUID 的 NSString,但当我尝试将其与另一个 NSString 进行比较时,结果很奇怪。

为什么这不会触发呢?这两个字符串肯定是匹配的吧?

NSString *myString = @"hello world";

if (myString == @"hello world")
    return;

这里也有一个很好的回答:https://dev59.com/JnA65IYBdhLWcg3wqAat - Emile
3个回答

253

使用-isEqualToString:方法比较两个字符串的值。使用C的 == 操作符将只比较对象的地址。

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

2
啊!非常感谢你。在这件事上感觉有点傻! - ingh.am
4
我猜在ObjectiveC++中,你可以创建一个操作符重载,用来让你使用==的语法糖能力,但是没有理智的Objective C程序员会这样做,因为在Objective C对象中,==只用于身份检查。 - Warren P

54

你可以根据需要使用大小写敏感或不敏感的比较方式。大小写敏感的比较方式如下:

if ([category isEqualToString:@"Some String"])
{
   // Both strings are equal without respect to their case.
}

大小写不敏感可以这么做:

if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
   // Both strings are equal with respect to their case.
}

1
我认为应该是: ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame) - JaakL
11
要小心使用“compare”函数,因为如果字符串(在本例中为“category”)为nil,compare将始终返回NSOrderedSame。 - nh32rg
这是一个很好的观点@nh32rg!! 为此加1分! isEqualToString有同样的问题吗? - badweasel

4
您可以使用以下函数比较字符串。
NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))  
NSLog(@"%d", (first == second)); 
NSLog(@"%d", [first isEqualToString:second]); 
NSLog(@"%d", [first isEqualToString:third]); 

Output will be :-
    0
    1
    1
    1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接