我想对数组进行排序。这是我的数组结构。
(
(
//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];
答案 1 :(得分: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);