Sorting core data position changes with sort descriptors for iPhone

限于喜欢 提交于 2019-12-05 10:24:28

Try this, assuming your positionChange is an NSNumber:

@interface NSNumber (AbsoluteValueSort)

-(NSComparisonResult) comparePositionChange:(NSNumber *)otherNumber;

@end

followed by:

@implementation NSNumber (AbsoluteValueSort)

-(NSComparisonResult) comparePositionChange:(NSNumber *)otherNumber
{
    return [[NSNumber numberWithFloat: fabs([self floatValue])] compare:[NSNumber numberWithFloat: fabs([otherNumber floatValue])]];
}

@end

and then do this:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"positionChange" ascending:NO selector:@selector(comparePositionChange:)];

and sort with that descriptor. If you want to make it so that -2 is always after 2, or 5 is always after -5 you can modify comparePositionChange: to return NSOrderedAscending in the cases when one number is the negative of the other.

The reason that code fails with the unsupported NSSortDescriptor selector error is that you're using a SQLite data store and attempting to use a Cocoa method as the sort descriptor. With a SQLite store, sort descriptors are translated on the fly into SQL and sorting is done by SQLite. That really helps performance but it also means that sorting is done in a non-Cocoa environment where your custom comparison method doesn't exist. Sorting like this only works for common, known methods and not for arbitrary Cocoa code.

A simple fix would be to do the fetch without sorting, get the results array, and sort that. Arrays can be sorted using whatever Cocoa methods you want, so med200's category should be useful there.

You could also change from a SQLite data store to a binary store, if your data set isn't very large.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!