使用键订购 NSArray

Order a NSArray with keys

我有一个包含以下数据的 NSArray;

(
    {
    3d = 0;
    cinemaId = 9;
    displayDate = "2015-08-19";
    end = "2015-08-20T00:14:00+02:00";
    hallIsLarge = 0;
    hfr = 0;
    id = 1505511;
    imax = 0;
    movieId = 19623;
    nl = 0;
    ov = 1;
    showId = 24422279;
    specialCode = "<null>";
    specialId = "<null>";
    start = "2015-08-19T22:00:00+02:00";
    status = 3;
    vip = 0;
},
    {
    3d = 1;
    cinemaId = 10;
    displayDate = "2015-08-19";
    end = "2015-08-20T00:25:00+02:00";
    hallIsLarge = 0;
    hfr = 0;
    id = 1504415;
    imax = 0;
    movieId = 16936;
    nl = 0;
    ov = 1;
    showId = 24436778;
    specialCode = "<null>";
    specialId = "<null>";
    start = "2015-08-19T22:05:00+02:00";
    status = 3;
    vip = 0;
},
    {
    3d = 0;
    cinemaId = 9;
    displayDate = "2015-08-19";
    end = "2015-08-20T00:08:00+02:00";
    hallIsLarge = 0;
    hfr = 0;
    id = 1506419;
    imax = 0;
    movieId = 21068;
    nl = 0;
    ov = 1;
    showId = 24422340;
    specialCode = "<null>";
    specialId = "<null>";
    start = "2015-08-19T22:10:00+02:00";
    status = 3;
    vip = 0;
},
    {
    3d = 0;
    cinemaId = 10;
    displayDate = "2015-08-19";
    end = "2015-08-20T00:08:00+02:00";
    hallIsLarge = 0;
    hfr = 0;
    id = 1504237;
    imax = 0;
    movieId = 21068;
    nl = 0;
    ov = 1;
    showId = 24436788;
    specialCode = "<null>";
    specialId = "<null>";
    start = "2015-08-19T22:10:00+02:00";
    status = 3;
    vip = 0;
}

)

我想按关键字 "start" 对字典进行排序。为此,我有:

NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"start" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
programmering = [programmering sortedArrayUsingDescriptors:sortDescriptors];

上面代码中是'programming'数组,但是好像不行。

我该怎么做才能完成这项工作? 提前感谢您的帮助。

programming 是一个数组,您希望在您的代码片段中对其进行排序。

您尝试排序的 key 是日期 string/ nsdate 对象。因此,您需要通过 nsdate 进行比较和排序。

这里假设你的数组是字典数组,这里yourArrayOfDicts

NSArray *sortedArray = [yourArrayOfDicts sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        //You will probably have to use nsdateformatter to convert your date string to valid nsdate objects
        // I am assuming you have the nsdate object here as the start key
        // if not make sure to convert it to a nsdate object for this to work
        NSDate *firstDate = obj1[@"start"];
        NSDate *secondDate = obj2[@"start"];
        return [firstDate compare:secondDate];        
    }];

这应该会给 sortedArray 排序。