Question

I have this mutable array of objects. These objects belong to a class called Property. This is a NSObject class that has one property that I have interest. This property is declared on Property class like this:

@property (readwrite, strong) NSNumber *selected;

A BOOL is stored on selected.

Now I have this mutable array that holds an array of Property objects.

I want to know how many of these objects have selected = YES at a given point.

OK, I can do this :

NSInteger count = 0;
for (Property *oneProperty in arrayProperties) {
  BOOL isSelected = [[oneProperty selected] boolValue];
  if (isSelected) count++;
}

and I will discover how many are selected but I know "Objective-C" has a lot of magic commands involving predicates, objectForKey and other stuff like that and I wonder if there is a way to do this using one of these magic commands.

Thanks.

Was it helpful?

Solution

You could use Key-Value coding:

NSInteger count = [[arrayProperties valueForKeyPath:@"@sum.selected"] integerValue];

OTHER TIPS

InsertWittyName's solution is the shortest.

Another approach you could use is the method indexesOfObjectsPassingTest.

In that method, you pass in a block of code that is applied to every object in the array. It creates an NSIndexSet that contains the indexes of all the objects for whom the code block returns true. index sets have a count property.

NSIndexSet *indexes = [arrayProperties indexesOfObjectsPassingTest: 
   ^BOOL (Property aProperty, NSUInteger i, BOOL *stop) {
            return [aProperty.selected boolValue];
        }];
count = indexes.count;

(Disclaimer: This code is untested, and I struggle a little with the syntax of blocks that take parameters and return values. I think I got it right...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top