ios - NSFetchedResultsController 对负字符串值进行排序

标签 ios sorting nsfetchedresultscontroller nssortdescriptor

我有 NSFetchedResultsController,它返回具有 index 属性的对象,index 属性是一个 NSString,例如我index 属性具有以下值:-1、-3、1、0、-2、3

我需要定义 NSSortDescriptor,它将根据 index 属性值对这些对象进行排序: -3, -2, -1, 0, 1, 3

我现在拥有的排序描述符无法正确排序负值。

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:ObjectIndex ascending:YES selector:@selector(localizedStandardCompare:)];

最佳答案

根据Apple Docs CoreData 的 SQLite 后备存储仅支持少数排序选择器:

... The SQL store, on the other hand, compiles the predicate and sort descriptors to SQL and evaluates the result in the database itself. This is done primarily for performance, but it means that evaluation happens in a non-Cocoa environment, and so sort descriptors (or predicates) that rely on Cocoa cannot work. The supported sort selectors are compare: and caseInsensitiveCompare:, localizedCompare:, localizedCaseInsensitiveCompare:, and localizedStandardCompare: (the latter is Finder-like sorting, and what most people should use most of the time).

(我的突出显示)。这些都无法实现您想要的。正如您所发现的,最后一个最接近:它将负数排在正数之前,并尝试数字排序(因此“23”排在“220”之前 - 文本排序会将它们倒过来)。但是(奇怪的是)负数是按照它们的绝对值排序的——所以“-1”出现在“-2”之前等等。果然,Finder 以相同的方式对负数进行排序。

所以我认为你最好的办法是重新设计你的数据库,使这个字段成为数字类型,这样你就可以使用合理的排序顺序。

关于ios - NSFetchedResultsController 对负字符串值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28938596/

相关文章:

ios - 将手势识别器添加到 SKShapeNode Swift 4

objective-c - 为什么 iOS 不通知我的应用程序有关 Audio Session 中断的信息?

java - 使 scala.Long 具有可比性

ios - NSFetchedResultsController:如何从实体的多对多关系中获取sectionName

objective-c - 核心数据崩溃 : Keypath Project not found in entity

具有自定义字体的 iOS navigationItem 标题失去垂直居中

ios - 如何使用 Swift 将文本复制到剪贴板/粘贴板

sorting - 在Solr中增强 bool 字段

c - 随机选择第 i 阶统计量

ios - NSFetchedResultsController 正在加载所有行,即使我已经设置了批处理