Comparing Strings in Cocoa

人盡茶涼 提交于 2019-12-17 02:31:44

问题


I have tried:

- (NSString*) generateString
{
    NSString* stringToReturn = @"thisString";
    return stringToReturn;
}

- (void) otherMethod
{
    NSString *returnedString = [self generateString];
    if (returnedString == @"thisString")
    { // Do this }
    else if (returnedString == @"thatString")
    { // Do that }
}

Which never matches.

I have then tried

if ([returnedString compare:@"thisString"] == 1)

But the compare method always returns 1 for me, even when comparing with a different string.

What is the correct way to do this, and what result should I expect?


回答1:


First of all, you are using the == operator to compare two object pointers (of type NSString *). So that returns true when the pointers are the same, not when the strings have the same contents. If you wanted to compare whether two strings are the same, you should use isEqualToString: or isEqual: (isEqual: is more general as it works for all types of objects).

Second, compare: returns 0 (NSOrderSame) when they are the same, and 1 (NSOrderedDescending) when the first is greater than the second. So in fact it returns 1 only when they are different (specifically, when the first is greater than the second).




回答2:


[returnedString isEqualToString: @"thisString"]



回答3:


When comparing two identical strings compare will return NSOrderedSame, which is 0. It can also return NSOrderedAscending, -1, and NSOrderedDescending, 1.

You may prefer to use isEqualToString which returns YES or NO.




回答4:


if ([returnedString isEqualToString:@"thisString"])
    NSLog(@"Equal");
else
    NSLog(@"Not Equal");



回答5:


The == operator when applied to objects check whether the pointers are equal.

You have to use -compare method or one of its companions -compare:options: -compare:options:range: or -compare:options:range:locale: which return a NSComparisonResult (NSOrderAscending, NSOrderSame, NSOrderDescending)

If you just need equality comparison, you can use -isEqualToString: which returns a BOOL value.



来源:https://stackoverflow.com/questions/881335/comparing-strings-in-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!