Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very custom order using NSSortDescriptor

Let's say I have objects with different statuses. Statuses are from 0 to 2. I need to sort them using NSSortDescriptor in this way:

1

2

0

Any suggestions?

like image 697
Paul Semionov Avatar asked Aug 24 '11 15:08

Paul Semionov


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 ...)
  }
}
like image 143
Rob Napier Avatar answered Nov 13 '22 22:11

Rob Napier


Use a custom comparator or selector. NSSortDescriptor has some methods you should take a look at. From the NSSortDescriptor Class Reference:

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

You will likely run into problems if you're passing these kinds of sort descriptors to a Core Data fetch request, though.

like image 25
Cameron Spickert Avatar answered Nov 13 '22 21:11

Cameron Spickert