开发者

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

I have an NSArray pop开发者_如何学Goulated with 0's and 1's. How can I return the number of 0's in the array?

Thanks!


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.


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


A little perverted solution :)

NSUInteger zeros_count(NSArray *array) {
  NSUInteger sum = 0;
  for (NSNumber *number in array)
    sum += [number intValue];
  return [array count] - sum;
}


KeyValueCoding

int count = [array count] - [[array valueForKeyPath:@"@sum.intValue"] intValue];


Declare a counter, set it to 0, loop through the array and if the element is 0, increment the counter.


NSArray* array = [[NSArray alloc] ...]; ; // put data into the array

NSUInteger arrayWithValue = 0;

for (NSNumber* number in array)

{

if ([number intValue] == NUMBERYOUARELOOKINGFOR)

    {
        count++;
    }
}


NSArray *arrayWithOnesAndZeros = @[@0, @0, @1, @1, @0, @1, @1, @0, @1];
NSUInteger numberOfZeros = [[NSCountedSet setWithArray:arrayWithOnesAndZeros]countForObject:@0];

This is a perfect method of you at runtime know very little of the object that you want to count, so instead of @0 you can put anyKindOfObjectWithUnknownValueOrType there instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜