My class has a property which is an enum
. This property is bound to an NSTableColumn
.
typedef enum _Status
{
Unknown=0,
Win,
OSX
} Status;
In order to make sure that NSTableColumn
shows the proper string representation, instead of displaying numeric 0, 1, and 2, I use an NSValueTransformer
.
So Unknown
becomes "Unknown OS". Win
becomes "MS Windows" and OSX
becomes "OSX 10.8". The table column displays these values correctly.
I need to sort the column using the transformed values. If I use
[NSSortDescriptor sortDescriptorWithKey:@"status"
ascending:YES
selector:@selector(compare:)];
the column is sorted in this order:
Unknown OS
MS Windows
OSX 10.8
which does make sense because 0 < 1 < 2. But I require it to be sorted using their string counterparts, which will make it:
MS Windows
OSX 10.8
Unknown OS
How can I do that without changing the order of enum?
You're using the standard compare:
method in your selector. It's just comparing the enums. Create your own method that compares the way you want. It can call your NSValueTransformer to get the string values, and you compare those, and return the appropriate NSComparisonResult.
[edit] OK my first suggestion won't work easily (without using categories). But something like this should. Assuming myValueTransformer is already instantiated, and your status is an NSNumber:
sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"status" ascending: YES
comparator:^(id first, id second){
NSNumber* firstNum = (NSNumber*)first;
NSNumber* secondNum = (NSNumber*)second;
if ([myValueTransformer transformedValue:firstNum] == [myValueTransformer transformedValue:secondNum]) {
return NSOrderedSame;
} else if ([myValueTransformer transformedValue:firstNum] > [myValueTransformer transformedValue:secondNum]) {
return NSOrderedDescending;
} else {
return NSOrderedAscending;
}
}];