views:

83

answers:

2

Ohh, what is wrong with this code !?!?!

    NSString *s1 = @"5 Oct 2010 18:30";
    NSString *s2 = @"5 Oct 2010 09:47";
    NSRange range = {0, 11}; // Both "D MMM YYYY " and "DD MMM YYYY"
    NSComparisonResult result = 0;
    result = [s1 compare:s2 options:NSLiteralSearch range:range];
    // result == -1
    NSString *sa = [s1 substringWithRange:range];
    NSString *sb = [s2 substringWithRange:range];
    result = [sa compare:sb];
    // result == 0

Why do I get different results from those two comperes? As far as I can tell, they should be same?

A: 

There's nothing wrong with it; sa and sb have the same values, but s1 and s2 do not.

EDIT:

Sorry, read it too quickly. There is indeed a problem - see below.

I use range in first comparison, isn't it supposed to be taken into account? Why else is it there?
JOM
Sorry - I see that now. Hmm...
I think the compiler makes sa and sb the same object - so that would explain why you get 0 in that case. But I still can't see why the first version doesn't work! I've experimented with a few variations, and I'm now confused...
I give up! I've posted a recipe to Apple's CocoaDev mailing list, and will let you know what response I get.
+3  A: 

Here's a better answer, thanks to the kind people at the CocoaDev mailing list!

The 'range' referred to in the method signature is the range of the receiving string only.

So, in your first example, you are comparing the characters in range of s1 with the whole of s2; and that, correctly, is reported as -1.

This explains the apparent anomaly noted by fluchtpunkt, as well.

Heh, many thanx for solution! Now I just need to figure out how such a disabled compare could be used. Not going to be easy...
JOM