首先创建一个包含字典的数组
NSDictionary * dic = @{@"num":@"1",@"key":@"ewedwedwed"};
NSDictionary * dic1 = @{@"num":@"4",@"key":@"frfefcerf"};
NSDictionary * dic2 = @{@"num":@"5",@"key":@"frfwdewdwderf"};
NSDictionary * dic3 = @{@"num":@"7",@"key":@"frfwdqerf"};
NSDictionary * dic4 = @{@"num":@"2",@"key":@"defg53y4"};
NSDictionary * dic5 = @{@"num":@"3",@"key":@"ded"};
NSMutableArray *arr = [NSMutableArray arrayWithObjects:dic,dic1,dic2,dic4,dic3,dic5, nil];
将用来判断 的字段存储到一个新的数组当中
NSMutableArray *valArr = [NSMutableArray array];
for (int i = 0; i < arr.count; i ++) {
NSDictionary *dic = arr[i];
NSString * str = [NSString stringWithFormat:@"%@-%d",dic[@"num"],i];
[valArr addObject:str];
}
然后根据索引进行排序
NSMutableArray *afterValArr = [valArr mutableCopy];
// 根据索引进行依次的排序
for (int i =0; i<[afterValArr count]-1; i++) {
for (int j = i+1; j<[afterValArr count]; j++) {
NSString *val1 = [afterValArr[i] componentsSeparatedByString:@"-"][0];
NSString *val2 = [afterValArr[j] componentsSeparatedByString:@"-"][0];
比较两个值的大小,小的在前,大的在后进行交换
if ([val1 intValue]>[val2 intValue]) {
//交换
[afterValArr exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
最后得到排序好的数组,可以根据情况选择相应的顺序
NSMutableArray *resultArr = [NSMutableArray array];//这个用来存放最后的结果
//小->大
for (int i = 0; i < arr.count; i ++) {
NSNumber * val = afterValArr[i];
NSInteger idx = [valArr indexOfObject:val];
[resultArr addObject:arr[idx]];
}
NSLog(@"resArr == %@",resultArr);
NSLog(@"resArr 0== %@",resultArr[0]);
NSMutableArray *modelArr = [NSMutableArray array];//存放倒序的数组
//倒序大->小
[modelArr addObjectsFromArray:[[resultArr reverseObjectEnumerator]allObjects]];
NSLog(@"modelArr == %@",modelArr);
NSLog(@"modelArr 0== %@",modelArr[0]);