首页 > NSSortDescriptor 应该如何用方法自定义排序规则?

NSSortDescriptor 应该如何用方法自定义排序规则?

小弟近日用 core data 进行数据同步时用到了NSFetchedResultController,但是在定义排序规则的时候遇到了麻烦,不知道到底
- (instancetype)initWithKey:(NSString *)keyPath ascending:(BOOL)ascending selector:(SEL)selector
这个方法应该怎么使用,主要问题在于不知道这个 selector 指的到底是哪里的方法,如果我想重载这个方法进行自定义的话,应该在哪个类里头进行重载?是我想排序的ManagedObject吗?


补充:我是看了苹果的官方文档对于这个方法的介绍,但是。。。看不懂啊有的地方(摔)。

The method to use when comparing the properties of objects, for example caseInsensitiveCompare: or localizedCompare:. The selector must specify a method implemented by the value of the property identified by keyPath. The selector used for the comparison is passed a single parameter, the object to compare against self, and must return the appropriate NSComparisonResult constant. The selector must have the same method signature as:
- (NSComparisonResult)localizedCompare:(NSString *)aString

其中不太懂的是引用中的粗体部分,我的理解是,这个方法是我的keyPath属性实现的一个方法,但是。。属性怎么实现方法?我知道我肯定理解的不对,求救助 QAQ


如果你要自定义排序规则,可以通过selector来指定。比如当前比较的属性类型为XXObject,那你就可以为它写一个分类,形如:

@interface XXObject (CustomCompare)
- (NSComparisonResult)customCompare:(XXObject *)other;
@end

@implementation XXObject (CustomCompare)
- (NSComparisonResult)customCompare:(XXObject *)other 
{
  if (<#self == other#>) 
  {
    return NSOrderedSame;
  }
  else if (<#self < other#>) 
  {
    return NSOrderedAscending;
  }
  else
  {
    return NSOrderedDescending;
  }
}

然后在selector的参数就是@selector(customCompare:)

【热门文章】
【热门文章】