我在自己的應用程序中通過創建NSSortDescriptor的自定義子類實現了這一點,這最終是NSArrayController用來執行排序的。實現如下,它並不複雜,但請注意,它將空字符串與零字符串一起排序。不幸的是,在Interface Builder中指定一個排序描述符子類是不可能的(至少我知道),所以你必須手動創建一個,然後調用setSortDescriptorPrototype:在你的awakeFromNib方法的適當的NSTableColumn中。
#define NULL_OBJECT(a) ((a) == nil || [(a) isEqual:[NSNull null]])
@interface MySortDescriptor : NSSortDescriptor {}
@end
@implementation MySortDescriptor
- (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]] autorelease];
}
- (NSComparisonResult)compareObject:(id)object1 toObject:(id)object2
{
if (NULL_OBJECT([object1 valueForKeyPath:[self key]]) ||
[[object1 valueForKeyPath:[self key]] length] == 0)
return ([self ascending] ? NSOrderedDescending : NSOrderedAscending);
if (NULL_OBJECT([object2 valueForKeyPath:[self key]]) ||
[[object2 valueForKeyPath:[self key]] length] == 0)
return ([self ascending] ? NSOrderedAscending : NSOrderedDescending);
return [super compareObject:object1 toObject:object2];
}
@end