给出具有核心数据的字符串的以下NSSortDescriptor:
[NSSortDescriptor sortDescriptorWithKey:@"series" ascending:true selector:@selector(caseInsensitiveCompare:)]
结果按字母顺序正确排序.但是,在系列为nil的情况下,具有nil值的字符串放在顶部,之后对非nil值进行排序,E.G:
[nil,nil,A,B,C,D...]
解决方法
虽然您无法将自定义选择器与Core Data一起使用,但您可以将NSSortDescriptor子类化以更改默认行为.像这样的东西应该工作:
#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