iOS NSArray排序

时间:2013-09-26 05:57:23

标签: ios nsarray nssortdescriptor

我有一个嵌套数组,想要通过内部数组中存在的键对其进行排序。 下面给出的是我想要使用NSSortDescriptor或其他方式排序的数组。

fares(
{
    pid = 1;
    type1 = (
    {
        color = "red";
        size = "big";
        properties = (
        {
            mod = "auto";
            payment = "EMI";
            moresegs = (
            {
                id = 141;
                name = "abcd";
                duration = "1 year"
            })
        })
    });
    type2 = (
    {
        color = "green";
        size = "small";
        properties = (
        {
            mod = "auto";
            payment = "EMI";
            moresegs = (
            {
                id = 141;
                name = "abcd";
                duration = "1 year"
            })
        })
    })
}

{
    pid = 1;
    type1 = (
    {
        color = "red";
        size = "big";
        properties = (
        {
            mod = "auto";
            payment = "EMI";
            moresegs = (
            {
                id = 141;
                name = "abcd";
                duration = "1 year"
            })
        })
    });
    type2 = (
    {
        color = "green";
        size = "big";
        properties = (
        {
            mod = "auto";
            payment = "EMI";
            moresegs = (
            {
                id = 141;
                name = "abcd";
                duration = "1 year"
            })
        })
    })
})

如何使用键“type2-> properties-> payment”对数组进行排序?

-------更新-----------

我修改了数组并使用了NSSortDescriptor解决了我的问题

2 个答案:

答案 0 :(得分:2)

试试这个:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"type1.size" ascending:YES];
NSArray *finalArray = [self.firstArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

答案 1 :(得分:0)

通过将fares数组输入此方法来尝试此操作 -

+(NSArray*)sortedListBySize:(NSArray*)_unsortedList{
    NSArray *sortedListBySize = [_unsortedList sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){

        if ([[obj1 valueForKeyPath:@"type2.properties.payments" ] intValue] < [[obj1 valueForKeyPath:@"type2.properties.payments"] intValue]) {
            return NSOrderedAscending;
        } else if ([[obj1 valueForKeyPath:@"type2.properties.payments" ] intValue] > [[obj1 valueForKeyPath:@"type2.properties.payments"] intValue]) {
            return NSOrderedDescending;
        }
        return NSOrderedSame;
    }];
    return sortedListBySize;
}