Objective-C 中的字符串比较

我目前已经建立了一个网络服务器,我通过 SOAP 与我的 iPhone 应用程序进行通信。我返回一个包含 GUID 的 NSString,当我试图将它与另一个 NSString进行比较时,我得到了一些奇怪的结果。

为什么不开火? 这两根弦肯定是匹配的吧?

NSString *myString = @"hello world";


if (myString == @"hello world")
return;
133634 次浏览

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

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

You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:

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

Case-insensitive is like this:

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

You can compare string with below functions.

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