使用密钥

时间:2015-08-19 20:26:24

标签: ios objective-c nsarray

我有一张带有以下数据的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];

在上面的代码中是'编程'数组,但似乎无法工作。

我可以做些什么来完成这项工作? 感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

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

这里假设你的数组是字典数组,这里是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排序。