Objective-C:计算类别中对象的有效方法

Ane*_*eel 2 algorithm dictionary objective-c

我在一组类别中有一堆对象.我想知道每个类别有多少.

在另一种语言中,我会创建一个字典,然后遍历这些对象,为每个对象增加字典中的相应值.但是,因为我无法在Objective-C中的NSDictionary中存储本机数字类型,所以我不断在NSNumber和数字类型之间来回转换:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for (MyObject *obj in objs) {  
    NSNumber *old = [dictionary objectForKey:obj.category];
    NSNumber *new = [NSNumber numberWithInteger:1 + old.integerValue];
    [dictionary setObject:new forKey:obj.category];
}
Run Code Online (Sandbox Code Playgroud)

有没有更有效的方法来做到这一点?

ben*_*ado 6

你在找NSCountedSet.

NSCountedSet *bag = [[NSCountedSet alloc] init];
for (MyObject *obj in objs) {  
    [bag addObject:obj.category];
}
for (id category in bag) {
    NSLog(@"%d instances of %@", [bag countForObject:category], category);
}
Run Code Online (Sandbox Code Playgroud)