I want a count on an array where a sub array meets a condition. I thought I could do this, but I can't.
NSLog(@"%d",[[_sections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[[obj objectAtIndex:4] isEqualToString:@"1"];
}] count]);
enumerateObjectsUsingBlock: doesn't return anything. I'd bet that code won't even compile (and, as your comment states, auto-completion doesn't work -- and it shouldn't).
Use NSArray's indexesOfObjectsPassingTest:
and take the count of the resulting NSIndexSet.
Documented here.
bbum is right; you should use indexesOfObjectsPassingTest. It's more straightforward.
But you could use enumerateObjectsUsingBlock to count test-passers, like this:
NSArray *sections = [NSArray arrayWithObjects:@"arb", @"1", @"misc", @"1", @"extra", nil];
NSMutableArray *occurrencesOf1 = [NSMutableArray array];
[sections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([(NSString*)obj isEqualToString:@"1"])
[occurrencesOf1 addObject:obj];
}];
NSLog(@"%d", [occurrencesOf1 count]); // prints 2
It's inefficient because it requires that extra mutable array.
(So you should check bbum's answer as the accepted one -- but I'm new at block functions too, and appreciated the puzzle.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With