【问题标题】:Bubble sort NSMutableArray冒泡排序 NSMutableArray
【发布时间】:2013-04-28 21:16:01
【问题描述】:

我已经使用 NSArray 函数 sortedArrayUsingComparator 在一些帮助下对 NSDictionaries 的 NSMutableArray 进行了排序,但是我想要排序的数组不仅仅是基于一个值。

有两个值,即 startdate 和 finishdate,目前我只按 startdate 排序,所以我的数组显示已排序,直到您查看 enddate 并发现它们不正确。

当前格式。

(start / end)
0 / 1996
0 / 1991
1992 / 1995
1993 / 1999
1993 / 1991

实际上我想实现这样的目标

(start / end)
0 / 1991
0 / 1996
1992 / 1995
1993 / 1991
1993 / 1999

这是我目前的代码

 // try sorting years
    NSString const * myStartDate = @"DATESTART";
    NSString const * myEndDate = @"DATEEND";

    NSArray *sortedArray = [resultantArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSDictionary *dictA = a;
        NSDictionary *dictB = b;

        NSNumber *startDate1 = dictA[myStartDate];
        NSNumber *startDate2 = dictB[myStartDate];

        return [startDate1 compare:startDate2];

    }];

这生成了我给你的第一个排序示例,我希望得到一点帮助的是对它进行排序,以便对具有相同开始日期和结束日期的任何内容进行排序。

任何帮助将不胜感激。

【问题讨论】:

  • 由于某种原因,使用 NSSortDescriptors 数组对您来说不可行吗?
  • @Eugene 我现在正在阅读有关 NSSortDescriptor 的信息。但事实是我迷失了我正在对开始和结束进行排序的事实......
  • 只需使用类似 [arr sortedArrayUsingDescriptors:@[[NSSortDescriptor key:startDate asc:YES], [NSSortDescriptor key:endDate asc:YES]]]; - 语法不正确,我现在无法访问 ide
  • 好的,谢谢,现在就试试。
  • 好吧,我在逗号后试了一下,我得到了这个错误 No known class method for selector 'key:asc:'

标签: objective-c nsmutablearray nsarray nsdictionary


【解决方案1】:

当我第一次尝试弄清楚如何使用数组中 NSDictionarys 的两个元素对 NSMutableArray 进行排序时,我不理解 NSSortDescriptors 所以我忽略了这里给出的示例

https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE

对于我的特殊问题,清单 2 是完美的解决方案。所以我自己编写了代码,效果很好!!!!

这是我的解决方案。

NSSortDescriptor *yearStartDesc = [[NSSortDescriptor alloc] initWithKey:@"YEARSTART" ascending:YES];
NSSortDescriptor *yearEndDesc = [[NSSortDescriptor alloc] initWithKey:@"YEARFINISH" ascending:YES];
NSArray *sortDescriptors = @[yearStartDesc, yearEndDesc];
NSArray *newSortedArray = [unsortedArray sortedArrayUsingDescriptors:sortDescriptors];

NSLog(@"%@", newSortedArray);

非常感谢大家帮助我。

【讨论】:

    猜你喜欢
    • 2012-02-09
    • 2013-10-09
    • 2015-09-12
    • 1970-01-01
    • 2014-03-26
    • 2015-03-06
    • 2018-04-18
    • 2018-11-13
    • 2011-08-04
    相关资源
    最近更新 更多