gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:34 25 4
gpt4 key购买 nike

我有以下排序描述符,用于对我的业务对象数组进行排序,准备显示在表格中,我从 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];

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

我想做的事情:

  1. 对整个数组进行排序,以便所有具有“awardedOn”集合的对象都显示在顶部
  2. 在两个“集合”中,按字母顺序排列
  3. 我不关心日期的实际值,我更感兴趣是否存在

像这样的(标题,粗体有awardedOn的值)

  • 很棒
  • 更好
  • 很酷
  • 另一个
  • 另一个
  • 再来一个
  • 又一个

最佳答案

您应该能够像您首先所说的那样使用两个描述符来做到这一点,首先是 awardedOn,然后是标题。但是,您需要为 awardedOn 排序提供一个自定义的 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 and Another/Another One/One More/Yet another。之后,你应该擅长:

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

最后一点,您可能需要做更多的工作,具体取决于您的“空”awardedOn 字段的外观(我假设,在上面的代码中,该字段设置为 null)。你可以在这里看看:https://stackoverflow.com/a/3145789

关于objective-c - 您可以使用 NSSortDescriptor 按非空值排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11098959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com