Reputation: 127
I was working on this:
NSString *str1 = @"This is string A";
NSString *str2 = @"This is string B";
NSComparisonResult compareResult;
if([str1 isEqualToString:str2] == YES)
NSLog (@"str1 == str2");
else
NSLog (@"str1 != str2");
compareResult = [str1 compare: str2];
if (compareResult == NSOrderedAscending)
NSLog (@"str1 < str2");
else if(compareResult == NSOrderedSame)
NSLog (@"str1 == str2");
else
NSLog (@"str1 > str2");
So my question is:
what is the difference between compare: and isEqualToString:
I am new to programming, so please bear with.
Thanks a lot.
Upvotes: 4
Views: 1884
Reputation: 6991
compare will give you an NSComparisonResult, which you can use to order stuff inside a tableView, like NSOrderedSame, or NSOrderedAscending and so on.
isEqualTo is an NSObject method which should be extended overriden by subclasses, like NSString (isEqualToString:), basically it compares an object with another object in a way you would expect it to, with the contents. [@"d" isEqualTo:@"d"] would return TRUE or 1
Upvotes: 0
Reputation: 7473
The compare: method allows you to determine the ordering of the objects so you can use it for sorting. The isEqualToString: is simply for determining whether two strings have the same value (note: it's comparing the value, not the objects).
Upvotes: 7
Reputation: 78363
isEqualToString: specifically tests the equality of two strings. This method is enhanced for string comparisons and only tests if two strings are equal (i.e., that they are the same).
compare: is a generic method for comparing two objects and is not necessarily enhanced for strings. compare: also returns the relative position of two objects, not just whether or not they are equal, but rather whether they are lesser than, equal to, or greater than the object to which they are being compared.
Upvotes: 2