ios - NSSortDescriptor 应该如何用方法自定义排序规则?
PHP中文网
PHP中文网 2017-04-17 14:22:50
[iOS讨论组]

小弟近日用 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

PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
大家讲道理

如果你要自定义排序规则,可以通过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:)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号