I've currently got a webserver set up which I communicate over SOAP with my iPhone app. I am returning a string containing a GUID and when I attempt to compare this with another string I get some strange results.
Why would this not fire? Surely the two strings are a match?
NSString *myString = @"hello world";
if(myString == @"hello world")
return;
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...
}
mxg
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
来源:https://stackoverflow.com/questions/2592511/string-comparison-in-objective-c