NSFetchedResultsController sort negative string values

I have NSFetchedResultsController which returns objects with index attribute, index attribute is a NSString and for example I have these values for index attribute: -1, -3, 1, 0, -2, 3

I need to define NSSortDescriptor which will sort these objects like this based on index attribute value: -3, -2, -1, 0, 1, 3

Sort descriptor that I have now which doesn't sort the negative values correctly.

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

According to the Apple Docs the SQLite backing store for CoreData supports only a handful of sort selectors:

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

(my highlighting). None of these achieves what you want. As you have found, the last of them comes closest: it sorts negative numbers before positive, and does attempt numerical ordering (so "23" is sorted before "220" - a text ordering would put them the other way round). But (bizarrely) negative numbers are sorted in order of their absolute value - so "-1" comes before "-2" etc. Sure enough, Finder sorts negative numbers in the same way.

So I think your best bet is to redesign your database to make this field a numeric type, so that you can use a sensible sort order.

链接地址: http://www.djcxy.com/p/36138.html

上一篇: 许多关系使用NSFetchedResultsController

下一篇: NSFetchedResultsController对负数字符串值进行排序