简体   繁体   中英

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?

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 ...)
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM