非常使用NSSortDescriptor的自定义订单

时间:2011-08-24 15:54:43

标签: iphone xcode nssortdescriptor

假设我有不同状态的对象。状态从0到2.我需要使用NSSortDescriptor以这种方式对它们进行排序:

1

2

0

有什么建议吗?

2 个答案:

答案 0 :(得分:6)

像这样(未经测试):

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

答案 1 :(得分:2)

使用自定义比较器或选择器。 NSSortDescriptor有一些方法你应该看看。来自NSSortDescriptor Class Reference

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

如果您将这些类型的排序描述符传递给Core Data fetch请求,则可能会遇到问题。