我有以下NSArray
具有 a 的内容NSDictionary
,我需要对它们进行排序,以便更高的字典值位于顶部。
我进行了研究,但找不到对我的 NSDictionary 进行排序的谓词。我怎样才能实现我的目标?
NSArray* result = @[@{ @"chest":[NSString stringWithFormat:@"%i",[chestR count]]},
@{@"back":[NSString stringWithFormat:@"%i",[backR count]]},
@{@"triceps":[NSString stringWithFormat:@"%i",[tricepR count]]},
@{@"biceps":[NSString stringWithFormat:@"%i",[bicepR count]]},
@{@"arms-other":[NSString stringWithFormat:@"%i",[armsR count]]},
@{@"legs":[NSString stringWithFormat:@"%i",[legsR count]]},
@{@"shoulders":[NSString stringWithFormat:@"%i",[shouldersR count]]},
@{@"abs":[NSString stringWithFormat:@"%i",[absR count]]},
@{@"cardio":[NSString stringWithFormat:@"%i",[cardioR count]]},
@{@"fitness":[NSString stringWithFormat:@"%i",[fitnessR count]]}
];
编辑和解决方案
这就是我解决问题的方法
NSArray* result = @[@{ @"chest":@"5"},
@{@"back":@"3"},
@{@"triceps":@"4"},
@{@"biceps":@"9"},
@{@"arms-other":@"1"},
@{@"legs":@"0"},
@{@"shoulders":@"2"},
@{@"abs":@"3"},
@{@"cardio":@"8"},
@{@"fitness":@"9"}
];
NSArray *sorted = [result sortedArrayUsingComparator:^(id obj1, id obj2){
NSArray *s1k = [obj1 allKeys];
NSInteger s1 = [obj1[[s1k objectAtIndex:0]] intValue];
NSArray *s2k = [obj2 allKeys];
NSInteger s2 = [obj2[[s2k objectAtIndex:0]] intValue];
if ( s1 > s2) {
return (NSComparisonResult)NSOrderedAscending;
} else if (s1 < s2) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];