2013-09-26 80 views
1

我有一个嵌套数组,并希望通过内部数组内的键进行排序。下面给出的 是我想用NSSortDescriptor或其他方式排序的数组。iOS NSArray排序

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->属性 - >支付”排序上面阵列?

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

我修改了阵列和使用NSSortDescriptor这解决了我的问题

+0

请格式化你的代码试试这个。与电脑不同,我们人类无法读取文字的随意挥霍。正确格式不难。去做就对了。 – Fogmeister

回答

2

试试这个:

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

Thnx Anil,但现在不工作我编辑了我的问题 –

+0

@PrafulKadam只是用“type2.properties.payment”替换此答案中的“type1.size”。这将排列你想要的数组。 – Fogmeister

+0

@Anil我试了这个,但给错误没有运气:-( –

0

通过输入查询票价阵列到这个方法 -

+(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; 
} 
+0

这是给误差支付不INTVALUE –

+0

支付不是intvalue- >这是我的假设,这就是为什么我写[付款(NSString)intValue]。你不需要使用它然后 - 只是使用[obj1 valueForKeyPath:@“type2.properties.payments”] <。 – Xcoder

+0

尝试这一点,但它是随机排序而不是通过付款键 –