How to count duplicates values in NSArray?

2019-03-09 13:37发布

Value of my NSArray includes the duplicates. I find the duplicates but now how can I find the no. they repeat?

3条回答
聊天终结者
2楼-- · 2019-03-09 14:09

You can use NSCountedSet for this. Add all your objects to a counted set, then use the countForObject: method to find out how often each object appears.

查看更多
贪生不怕死
3楼-- · 2019-03-09 14:13

You can try something like this

__block NSInteger elementCount = 0;
NSArray *array;

[<#NSArray yourArray#> indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    if (obj == <#yourObject#>) {
        elementCount++;
        return YES;
    }
    return NO;
}];

Let me know if that works for you

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-09 14:28

Example:

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];

for (id item in set) {

    NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
查看更多
登录 后发表回答