Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

objective c - Comparing Strings in Cocoa

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...