Find the average of an NSMutableArray with valueForKeyPath

╄→尐↘猪︶ㄣ 提交于 2019-12-01 06:01:44

You need to use @avg.floatValue (or @avg.doubleValue, or what have you). The @avg operator will average the property of the objects in the array specified by the name after the dot. The documentation is confusing on this point, but that is what:

to get the values specified by the property specified by the key path to the right of the operator

Is saying. Since you have a collection of NSNumber objects, you use one of the *value accessors, e.g. floatValue to get the value of each object. As an example:

#include <Foundation/Foundation.h>

int main(void) {
  NSMutableArray *ma = [NSMutableArray array];
  [ma addObject:[NSNumber numberWithFloat:1.0]];
  [ma addObject:[NSNumber numberWithFloat:2.0]];
  [ma addObject:[NSNumber numberWithFloat:3.0]];

  NSLog(@"avg = %@", [ma valueForKeyPath:@"@avg.floatValue"]);

  return 0;
}

Compiling and running this code returns:

$ clang avg.m -framework Foundation -o avg
steve:~/code/tmp
$ ./avg 
2013-01-18 12:33:15.500 avg[32190:707] avg = 2
steve:~/code/tmp

The nice thing about this approach is that this work for any collection, homogenous or otherwise, as long as all objects respond to the specified method, @avg will work.

EDIT

As pointed in the comments, the OP's problem is that he is averaging a collection with one element, and thus it appears to simply print the contents of the collection. For a collection of NSNumber objects, @avg.self works just fine.

No, you can't do like this. The object Transaction is a Modal Class. This class is having three properties, namely

  • payee
  • amount
  • date

Each row in this image represents one Transaction modal object.

transactions is an array which is holding all these rows (Transaction Modal Objects).

In these transactions array, they are trying to calculate the Transaction Modal amount field average using the operator @avg. So, its like

NSNumber *transactionAverage = [transactions valueForKeyPath:@"@avg.amount"];

your array doesn't have the key self. So that's the problem

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