2016-03-21 97 views
-1

我想對數組進行排序。這裏是我的Array結構。如何對包含數組和字典的數組進行排序鍵號

(

    (

     //SubArray 
) 

{ 
    date =「2016-03-16」; 
} 

) 

------ 
------ 

如何使用排序描述符進行排序?

可能嗎? (或)

我是否需要改變我的數組結構(將子數組移動到字典..)。

+0

請問我可以知道倒票的原因 –

回答

1

把你的字典到一個數組,這樣做

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; 
yourArray=[yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; 
dictionaryArray = [yourArray copy]; 
+0

@idevloper,但是我需要頂級數組屬於那個日期 –

+0

你的答案不適用於與該問題有關的問題,你是否看到過這個'( // Array )',你如何排序這 –

0

下面就是我的回答試試這個,如果它幫助,它長期的解決方案,但它幫助我獲得數組這是短期明智日期

// my Json responce in string 
    NSString *Str = @"{\"Array\":[{\"date\":\"01/15/2016\",\"Subarr\":[\"A\",\"B\"]},{\"date\":\"01/06/2016\",\"Subarr\":[\"C\",\"D\"]},{\"date\":\"16/02/2015\",\"Subarr\":[\"E\",\"F\"]},{\"date\":\"22/02/2016\",\"Subarr\":[\"G\",\"H\"]}]}"; 
    // convert in to nsdata 
    NSData *data = [Str dataUsingEncoding:NSUTF8StringEncoding]; 
    // final json responce 
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    // create a new Dictionary for shorting 
    NSMutableDictionary *Dic = [[NSMutableDictionary alloc] init]; 
    // get all main array 
    NSArray *Temp1 = [json valueForKey:@"Array"]; 
    for (int i = 0; i<Temp1.count; i++) { 
     id subjson = Temp1[i]; 
     // get date and store in key string 
     NSString *Key = [subjson valueForKey:@"date"]; 
     // get sub array and store in array object 
     NSArray *Object = [subjson valueForKey:@"Subarr"]; 
     // now store object with key is date 
     [Dic setObject:Object forKey:Key]; 
    } 
    // after get all key from created Dictionary 
    NSArray *keys = [Dic allKeys]; 
    // short key date wise 
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { 
     NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
     [format setDateFormat:@"DD/MM/YYYY"]; 
     NSDate *FirstDate = [format dateFromString:a]; 
     NSDate *SecondDate = [format dateFromString:b]; 
     return [FirstDate compare:SecondDate];; 
    }]; 
    // you can get short array by date wise 
    NSLog(@"%@",sortedArray); 
    // now you want array which is short wise date 
    NSMutableArray *Final_shortarr = [[NSMutableArray alloc] init]; 
    for (int i=0; i<sortedArray.count; i++) { 
     NSString *Key = [sortedArray objectAtIndex:i]; 
     [Final_shortarr addObject:[Dic objectForKey:Key]]; 
    } 
    // this array give final short datewise array 
    NSLog(@"%@",Final_shortarr); 
+0

看來你已經添加子字典到字典? –

+0

是與關鍵是日期 –

+0

如果我改變我的陣列結構像移動子陣列到字典,解決方案是非常簡單的像上面的答案。 –

相關問題