Quick way to sum a property of all objects within

2020-02-13 22:43发布

问题:

I thought there was a way to quickly ask a NSSet to poll its members and return a sum of say an NSInteger property in each of its objects, but I may very well be confusing this with the Mac OS X side of things. Does this exist in Cococa Touch?

The closest thing I can find is objectEnumerator, whereby I suppose I could rifle through each object and increment my own variable. Does the better way exist?

回答1:

If you're trying to find the sum of a given property (theIntegerPropertyToSum) for each member of an array/set-derived class that's KVC-compliant (theSet), you can do the following:

NSNumber* theSum = [theSet valueForKeyPath:@"@sum.theIntegerPropertyToSum"];


回答2:

Why not use plain objective C (2)?

NSInteger theSum = 0;
for (id obj in theSetOrArray)
    theSum += obj.theIntegerPropertyToSum;

Disadvantage: If you like to count lines, then this looks longer. Are there other disadvantages - I wonder what happens with the KVC method with objects that don't have the required 'theIntegerPropertyToSum' property?

Advantage: I would bet that this debugs and performance tests easier. Plus when someone else reads your code in a year or two they will know what is going on here - whether they have ever seen a line of objective C or not, this looks like what is actually happening.