按对象出现在该数组中的次数对数组进行排序

时间:2013-05-07 17:37:31

标签: ios nsarray nsdictionary nssortdescriptor nscountedset

我迷失在排序描述符,词典和计数集的海洋中。希望有人能帮助我找到一种更简单的方法。

从这样的排序数组开始(NSNumbers):

['7','7','7','5','5','5','5','5','5','3','2','2','2','2']

我希望最终得到一个排序的字典数组,如下所示:

{'5','6'} //the number 5 appeared 6 times
{'2','4'} //the number 2 appeared 4 times
{'7','3'} //the number 7 appeared 3 times
{'3','1'} //the number 3 appeared 1 time

1 个答案:

答案 0 :(得分:5)

以下是根据NSCountedSet

执行您所需的内容的代码段
NSArray *numbers = @[@7,@7,@7,@5,@5,@5,@5,@5,@5,@3,@2,@2,@2,@2];

NSCountedSet *countedSet = [NSCountedSet setWithArray:numbers];

NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSNumber *num in countedSet) {
    NSUInteger c = [countedSet countForObject:num];
    [result setObject:@(c) forKey:num];
}