开发者

How to count duplicates values in NSArray?

Value of my NSArray includes the duplicates. I find the duplicates but now how can I开发者_JAVA技巧 find the no. they repeat?


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.


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]);
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜