Very custom order using NSSortDescriptor

我的未来我决定 提交于 2019-12-06 04:56:57

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7178526/very-custom-order-using-nssortdescriptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!