我有下面的NSArray,它有一个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;
}];发布于 2013-07-23 21:19:17
字典不是按定义排序的。
您可以将其转换为数组。NSDictionary实例方法-allValues可能适合这样做。
然后,您可以使用自定义排序描述符对新数组进行排序,以确保按您希望的方式对其进行排序。
https://stackoverflow.com/questions/17821130
复制相似问题