Very custom order using NSSortDescriptor

Let's say I have objects with different statuses. Statuses from 0 to 2. I need to sort them using NSSortDescriptor as follows:

1

2

0

Any suggestions?

+4
source share
2 answers

Something like this (untested):

descriptor = [[[NSSortDescriptor alloc] initWithKey:@"status" ascending:YES selector:@selector(customStatusCompare:)] autorelease]; @interface NSNumber (CustomStatusCompare) - (NSComparisonResult)customStatusCompare:(NSNumber*)other; @end @implementation NSNumber (CustomStatusCompare) - (NSComparisonResult)customStatusCompare:(NSNumber*)other { NSAssert([other isKindOfClass:[NSNumber class]], @"Must be a number"); if ([self isEqual:other]) { return NSOrderedSame; } else if (... all your custom comparison logic here ...) } } 
+6
source

Use your own comparator or selector. NSSortDescriptor has some methods that you should pay attention to. From the Link to the NSSortDescriptor Class :

 + sortDescriptorWithKey:ascending:selector: – initWithKey:ascending:selector: + sortDescriptorWithKey:ascending:comparator: – initWithKey:ascending:comparator: 

You will probably run into problems if you pass these types of sort descriptors to a Core Data fetch request.

+2
source

All Articles