控制NSSortDescriptor在Core Data中对nil值排序的方式 [英] Controlling the way NSSortDescriptor sorts nil values in Core Data

查看:172
本文介绍了控制NSSortDescriptor在Core Data中对nil值排序的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有Core Data的字符串,给出以下 NSSortDescriptor

Given the following NSSortDescriptor for strings with Core Data:

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

结果按字母顺序升序排列。但是系列 nil 的情况下, nil 值放在顶部,非nil值随后排序,EG:

The results are correctly ordered alphabetically ascending. However in instances where series is nil, strings with nil values are placed at the top, with non-nil values being sorted thereafter, E.G:

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

有没有办法控制这种行为?核心数据不允许自定义选择器。这里有一个类似的问题(不解决Core Data的限制):

Is there any way to control this behavior? Core Data does not allow for custom selectors. Here's a similar question to mine (not addressing Core Data's limitation, however):

NSSortDescriptor和nil值

推荐答案

虽然您无法使用自定义选择器,您可以子类化 NSSortDescriptor 以更改默认行为。这样的东西应该工作:

While you cannot use a custom selector with Core 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

这篇关于控制NSSortDescriptor在Core Data中对nil值排序的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆