Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the objects in an NSArray that have a certain value?

Tags:

cocoa

nsarray

I have an NSArray populated with 0's and 1's. How can I return the number of 0's in the array?

Thanks!

like image 551
Jonah Avatar asked Nov 22 '25 09:11

Jonah


2 Answers

Depending on your application, you might consider using an NSCountedSet.

When it comes time to get the count of a certain type of object, you can just use the countForObject: instance method.

Probably a little too heavy for your current problem, but may be useful for others looking for similar solution.

like image 125
Reed Olsen Avatar answered Nov 24 '25 23:11

Reed Olsen


Iterate through the array and count the things you're looking for.

Assuming you have an NSArray populated with NSNumbers:

NSArray* array = ... ; // populate array
NSUInteger count = 0;
for (NSNumber* number in array)
{
    if ([number intValue] == 0)
    {
        count++;
    }
}
like image 24
Shaggy Frog Avatar answered Nov 24 '25 21:11

Shaggy Frog



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!