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?
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 ...)
}
}
integerValue
to get to a simple integer. Compare them with <, = and > and return NSOrderedDescending
, NSOrderedSame
, or NSOrderedAscending
based on how you want them to be ordered. In your case, if [self integerValue]
is 1, then it's always NSOrderedAscending
(since we already checked for equality). If it's 0, then it's always NSOrderedDescending
. If it's 2, then you need to check the other value to figure out which to return. –
Resuscitate customStatusCompare:
? –
Resuscitate if ([self isEqual:[NSNumber numberWithInt:2]]) { return NSOrderedSame; }
seems wrong. You need to actually check the value of status
in this case. BTW, I would also pull out the value into an int
and do your work that way rather than generating so many NSNumber
objects. That's fairly optimized, but this code still gets called a lot. –
Resuscitate 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.
© 2022 - 2024 — McMap. All rights reserved.