0

我迷失在分类描述符、字典和计数集的海洋中。希望有人可以帮助我找到更简单的方法。

从这样的排序数组开始(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
4

1 回答 1

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];
}
于 2013-05-07T18:03:18.940 回答