views:

207

answers:

2

I may very well be confusing this with the Cocoa (Mac OS X) side of things so it may not exist in Cocoa-Touch...but 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?

Closest I can find is objectEnumerator whereby I suppose I could rifle through each object and increment my own int sum variable. Better way?

+2  A: 

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"];
Nathan de Vries
This is great! Where, btw, is it documented? I can't seem to find anything in/around the definition of "valueForKeyPath:" in the KVC Protocol Reference...
Meltemi
A: 

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.

Tom Andersen
Your answer implies that you've not used or read the documentation on KVC -- you might want to read about it before saying it shouldn't be used.In your "plain objective C (2)" example, what happens when theIntegerPropertyToSum is undefined, or one value of theIntegerPropertyToSum is -1 and another is 1.2? What if it's nil?
Nathan de Vries
I use KVC all the time - to let the UI communicate with the code. The disadvantage of [theSet valueForKeyPath:@"@sum.theIntegerPropertyToSum"] is that is a language construct that does not show at a glance what is going on. Any javascript C, C# programmer seeing the valueForKeyPath statement will not understand it - and be sucked into a time consuming lesson in order to figure out what one line of code does. Never use language specific constructs unless you need them. Reminds me of STL C++ code, which is unreadable to all but STL experts.
Tom Andersen
Sounds like you use KVO all the time, not KVC.
Nathan de Vries