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?
Best Solution
First of all, you are using the
==
operator to compare two object pointers (of typeNSString *
). 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 useisEqualToString:
orisEqual:
(isEqual:
is more general as it works for all types of objects).Second,
compare:
returns0
(NSOrderSame
) when they are the same, and1
(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).