Controlling how NSSortDescriptor sorts nil values ​​in Core Data

Given the following NSSortDescriptor for rows with master data:

 [NSSortDescriptor sortDescriptorWithKey:@"series" ascending:true selector:@selector(caseInsensitiveCompare:)] 

Results are sorted alphabetically in ascending order. However, in cases where series is nil , lines with nil values ​​are placed at the top, after which non-nil values ​​are sorted, EG:

 [nil, nil, nil, A, B, C, D...] 

Is there a way to control this behavior? Master data does not allow you to configure the selector. Here's a similar question for mine (without resorting to limiting the master data):

NSSortDescriptor and nil Values

+7
ios objective-c core-data
source share
1 answer

While you cannot use a custom selector with master data, you can subclass NSSortDescriptor to change the default behavior. Something like this should work:

 #define NULL_OBJECT(a) ((a) == nil || [(a) isEqual:[NSNull null]]) @interface NilsLastSortDescriptor : NSSortDescriptor {} @end @implementation NilsLastSortDescriptor - (id)copyWithZone:(NSZone*)zone { return [[[self class] alloc] initWithKey:[self key] ascending:[self ascending] selector:[self selector]]; } - (id)reversedSortDescriptor { return [[[self class] alloc] initWithKey:[self key] ascending:![self ascending] selector:[self selector]]; } - (NSComparisonResult)compareObject:(id)object1 toObject:(id)object2 { if (NULL_OBJECT([object1 valueForKeyPath:[self key]]) && NULL_OBJECT([object2 valueForKeyPath:[self key]])) return NSOrderedSame; if (NULL_OBJECT([object1 valueForKeyPath:[self key]])) return NSOrderedDescending; if (NULL_OBJECT([object2 valueForKeyPath:[self key]])) return NSOrderedAscending; return [super compareObject:object1 toObject:object2]; } @end 
+8
source share

All Articles