加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 您可以使用NSSortDescriptor按值排序为空吗?

发布时间:2020-12-16 07:31:11 所属栏目:百科 来源:网络整理
导读:我有以下排序描述符排序我的业务对象数组,准备在表中显示,我开始从 previous SO question的一些示例排序代码 NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"awardedOn" ascending:NO];NSSortDescriptor *sortDescriptor2 =
我有以下排序描述符排序我的业务对象数组,准备在表中显示,我开始从 previous SO question的一些示例排序代码

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"awardedOn" ascending:NO];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor1,sortDescriptor2,nil];
NSArray *sortedArray = [returnable sortedArrayUsingDescriptors:sortDescriptors];

我正在显示的所有对象都有一个标题.其中只有一些会有一个“awardOn”设置,这是一个NSDate.

我想做的事:

>对整个数组进行排序,以便设置“awardOn”的所有对象都是
显示在顶部
>在两个“集合”中,按字母顺序排序
>我不关心约会的实际价值,我更感兴趣
如果它存在或不存在

像这样的东西(标题,大胆的,具有awardOn的价值)

>太棒了
>更好
>酷
>另一个
>另一个
>还有一个
>又一个

解决方法

您应该能够使用两个描述符,例如您首先说的,首先是awardOn,然后是标题.但是,您需要为awardOn排序提供一个自定义NSSortDescriptor,看起来像这样:

#define NULL_OBJECT(a) ((a) == nil || [(a) isEqual:[NSNull null]]) 
@interface AwardedOnSortDescriptor : NSSortDescriptor {} 
@end 
@implementation AwardedOnSortDescriptor 
- (id)copyWithZone:(NSZone*)zone 
{ 
    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]])) { 
        if (NULL_OBJECT([object2 valueForKeyPath:[self key]]))  
            return NSOrderedSame; // If both objects have no awardedOn field,they are in the same "set"
        return NSOrderedDescending; // If the first one has no awardedOn,it is sorted after         
    } 
    if (NULL_OBJECT([object2 valueForKeyPath:[self key]])) { 
        return NSOrderedAscending; // If the second one has no awardedOn,it is sorted after
    } 
    return NSOrderedSame; // If they both have an awardedOn field,they are in the same "set"
} 
@end

这将允许您必须单独设置:Awesome / Better / Cool和Another / Another One / One More /还有另一个,在您的示例中.在那之后,你应该善于:

NSSortDescriptor *sortDescriptor1 = [[AwardedOnSortDescriptor alloc] initWithKey:@"awardedOn" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];

最后一点,你可能需要更多的工作,这取决于你的“空”awardOn字段的样子(我假设,在上面的代码中,字段被设置为null).你可以看看这里:https://stackoverflow.com/a/3145789

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读