Objective-C: Count the number of times an object occurs in an array?
One more solution, using blocks (working example):
NSInteger occurrences = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:@"Apple"];}] count];NSLog(@"%d",occurrences);
As @bbum said, use an NSCounted set. There is an initializer thet will convert an array directly into a counted set:
NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"X", @"B", @"C", @"D", @"B", @"E", @"M", @"X", nil]; NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array]; NSLog(@"%@", countedSet);
NSLog output: (D [1], M [1], E [1], A [1], B [3], X [2], C [1])
Just access items:
count = [countedSet countForObject: anObj]; ...
A Simple and specific answer:
int occurrences = 0;for(NSString *string in array){ occurrences += ([string isEqualToString:@"Apple"]?1:0); //certain object is @"Apple"}NSLog(@"number of occurences %d", occurrences);
PS: Martin Babacaev's answer is quite good too. Iteration is faster with blocks but in this specific case with so few elements I guess there is no apparent gain. I would use that though :)