2013-09-26 150 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

嘗試這一點,但它是隨機排序而不是通過付款鍵 –