I have a CoreData entity with two attributes. One called 'position' the other called 'positionChange'. Both of them are integers where the position attribute is the current position and the positionChange is the difference between the previous position and the new position. This means that the positionChange can be negative.
Now I would like to sort by positionChange. But I would like it to disregard the negative values. Currently I'm sorting it descending, which will give the result: 2, 1, 0, -1, -2. But what I'm looking for is to get this result: 2, -2, 1, -1, 0.
Any ideas on how to solve this using sort descriptors?
EDIT
I got 2 classes, one called DataManager and the other containing my NSNumber category (positionChange is of type NSNumber).
In DataManager I have a method called 'fetchData:' where I'm executing my fetch request with a sort descriptor:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"positionChange" ascending:NO selector:@selector(comparePositionChange:)];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
I'm doing some more stuff to the request, but that's not interesting for this issue.
My NSNumber category should be exactly like the one you posted: In the .h:
@interface NSNumber (AbsoluteValueSort)
- (NSComparisonResult)comparePositionChange:(NSNumber *)otherNumber;
@end
And in the .m:
@implementation NSNumber (AbsoluteValueSort)
- (NSComparisonResult)comparePositionChange:(NSNumber *)otherNumber
{
return [[NSNumber numberWithFloat:fabs([self floatValue])] compare:[NSNumber numberWithFloat:fabs([otherNumber floatValue])]];
}
@end
When I call fetchData on my DataManager object I get this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unsupported NSSortDescriptor selector: comparePositionChange:'
Any ideas of what might be the case? I have included my NSNumber category header file in my DataManager class.
absolutePositionChange
field to the model and populate it (in the setter forpositionChange
, if there is one) withabs(positionChange)
? You could use that field in your sort descriptor. – Diley