【问题标题】:How to sort an array in descending order in iPhone [duplicate]如何在iPhone中按降序对数组进行排序[重复]
【发布时间】:2014-01-04 20:59:42
【问题描述】:

我正在尝试按降序对数组进行排序,我可以按升序对数组进行排序,这是我按升序排序的代码,

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"year" ascending:NO];
NSArray * descriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
sortedArray = [array sortedArrayUsingDescriptors:descriptors];

dictionaryWithSortedYears = [[NSMutableDictionary alloc] init];
NSString *tempDateKey = nil;

for (TreeXmlDetails *list in sortedArray)
{
    id obj = [dictionaryWithSortedYears objectForKey:list.year];

    if(!obj)
    {
        if(tempDateKey == nil)
        {
            arrayFromList = [[NSMutableArray alloc] init];
            tempDateKey = list.year;
        }
    }

    if([list.year isEqualToString:tempDateKey])
        [arrayFromList addObject:list];
    else
    {
        [dictionaryWithSortedYears setObject:arrayFromList forKey:tempDateKey];
        tempDateKey = nil;
        arrayFromList = nil;
        arrayFromList = [[NSMutableArray alloc] init];
        tempDateKey = list.year;
        [arrayFromList addObject:list];
    }
}

[dictionaryWithSortedYears setObject:arrayFromList forKey:tempDateKey];

NSArray *arr = [dictionaryWithSortedYears allKeys];

sortedKeys = [[NSArray alloc] initWithArray:[arr sortedArrayUsingSelector:@selector(compare:)]];

但是,我想对数组进行降序排序,请帮帮我。 提前致谢。

【问题讨论】:

    标签: ios iphone objective-c nsarray nssortdescriptor


    【解决方案1】:

    使用以下内容:

    [yourArrayToBeSorted sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [(NSDate *)obj2 compare:(NSDate *)obj1];} ];
    

    【讨论】:

    • 你必须拥有 NSMutableArray 类型的 'yourArrayToBeSorted'。
    【解决方案2】:

    来自文档:

    NSSortDescriptor 的一个实例描述了排序对象的基础 通过指定用于比较对象的属性,方法 用于比较属性,以及是否应该进行比较 升序或降序。 NSSortDescriptor 的实例是不可变的。

    您通过指定键来构造 NSSortDescriptor 的实例 要比较的属性的路径,排序的顺序(升序 或降序),以及(可选)用于执行 比较。

    构造函数: initWithKey:ascending:

    返回使用给定属性初始化的 NSSortDescriptor 对象 键路径和排序顺序,以及默认的比较选择器。 - (id)initWithKey:(NSString *)keyPath 升序:(BOOL)升序

    指定顺序的参数:

    ascending YES 如果接收方指定按升序排序, 否则否。

    这些苹果文档会逐步指导您如何对数组进行排序:

    https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/SortDescriptors/Articles/Creating.html

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多