Thursday 6 December 2012

Compare method for Sorting an Array

It's pretty simple to write your own comparison method for strings: 
@implementation NSString(compare)

-(NSComparisonResult)compareNumberStrings:(NSString *)str {
    NSNumber * me = [NSNumber numberWithInt:[self intValue]];
    NSNumber * you = [NSNumber numberWithInt:[str intValue]];

    return [you compare:me];
}

@end
share|edit

feedback
You should use this method:
[arr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
in a NSArray or:
[arr sortUsingSelector:@selector(caseInsensitiveCompare:)];
in a "inplace" sorting NSMutableArray
The comparator should return one of this values:
  • NSOrderedAscending
  • NSOrderedDescending
  • NSOrderedSame
  •  
  •  -(NSComparisonResult)compare:(id)anotherObject
  • {
            NameAndHighScore *that= (NameAndHighScore*)anotherObject;
            if( this.highScore < that.highScore ) return NSOrderedDescending;
            if( this.highScore > that.highScore ) return NSOrderedAscending;
            else return NSOrderedSame;
    }
     
    static NSComparisonResult compareObjects(id obj1, id obj2, void* context) {
     int value1 = [obj1 intValue], value2 = [obj2 intValue];
     if (value1 < value2) return NSOrderedDescending;
     if (value1 > value2) return NSOrderedAscending;
     return NSOrderedSame;
    } 

No comments:

Post a Comment