Let's say I have objects with different statuses. Statuses are from 0 to 2. I need to sort them using NSSortDescriptor in this way:
1
2
0
Any suggestions?
Something like this (untested):
descriptor = [[[NSSortDescriptor alloc]
initWithKey:@"status"
ascending:YES
selector:@selector(customStatusCompare:)] autorelease];
@interface NSNumber (CustomStatusCompare)
- (NSComparisonResult)customStatusCompare:(NSNumber*)other;
@end
@implementation NSNumber (CustomStatusCompare)
- (NSComparisonResult)customStatusCompare:(NSNumber*)other {
NSAssert([other isKindOfClass:[NSNumber class]], @"Must be a number");
if ([self isEqual:other]) {
return NSOrderedSame;
}
else if (... all your custom comparison logic here ...)
}
}
Use a custom comparator or selector. NSSortDescriptor
has some methods you should take a look at. From the NSSortDescriptor Class Reference:
+ sortDescriptorWithKey:ascending:selector:
– initWithKey:ascending:selector:
+ sortDescriptorWithKey:ascending:comparator:
– initWithKey:ascending:comparator:
You will likely run into problems if you're passing these kinds of sort descriptors to a Core Data fetch request, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With