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

て烟熏妆下的殇ゞ 提交于 2019-11-28 07:35:53

问题


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.



来源:https://stackoverflow.com/questions/1107299/quick-way-to-sum-a-property-of-all-objects-within-an-nsset

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