Comparing strings of different lengths with parameters compare: options: range: produces the wrong result

Why is this comparison obtained in NO?

BOOL areTheSame = NSOrderedSame == [@"th" compare:@"They" options:NSCaseInsensitiveSearch range:NSMakeRange(0, 2)];

When I test it on @"th"and @"th", it is YES.

What am I missing here?

+3
source share
1 answer

This is counterintuitive, but the argument rangeapplies only to the recipient. The length of the other line (argument compare:) is not limited by the range. Your call reduces @"th"to the range {0,2} that it produces @"th"(ie It doesn’t work), and then compares it to @"They".

You will see that it is:

NSComparisonResult comp = [@"They" compare:@"th" 
                                   options:NSCaseInsensitiveSearch 
                                     range:NSMakeRange(0, 2)];
BOOL areTheSame = comp == NSOrderedSame;

, (@"They") ( @"th"), .

+6

All Articles