Quick way to sum a property of all objects within an NSSet?

拟墨画扇 提交于 2019-11-29 13:49:54

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"];

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!