Search code examples
cocoansarray

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


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

Thanks!


Solution

  • 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++;
        }
    }