Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional nsarray count

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]);
like image 487
Darren Avatar asked Jun 27 '26 00:06

Darren


2 Answers

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.

like image 86
bbum Avatar answered Jun 29 '26 15:06

bbum


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.)

like image 38
Wienke Avatar answered Jun 29 '26 14:06

Wienke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!