开发者

What is the difference between compare: and isEqualToString:?

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");    

comp开发者_开发技巧areResult = [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.


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).


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜