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

cocoa-touch, nsstring, objective-c, string-comparison

Solution

This is counter-intuitive, but the `range` argument only applies to the receiver. The length of the other string (the argument to `compare:`) isn't range-limited. Your call reduces `@"th"` to the range {0,2}, which produces `@"th"` (i.e., this has no effect), and then compares it to `@"They"`.

You will see that this:

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

produces the result you expect, because it cuts the receiver (`@"They"`) down (to `@"Th"`) and then does the comparison.

Problem

Why does this comparison result in `NO`? ``` BOOL areTheSame = NSOrderedSame == [@"th" compare:@"They" options:NSCaseInsensitiveSearch range:NSMakeRange(0, 2)]; ``` When I test it on `@"th"` and `@"Th"` it's `YES`. What am I missing here?

Original source