Pancho
Pancho

Reputation: 4143

Get average value from NSManagedObject request array

I need to get an average price from my NSManagedObject array. I have executed NSFetchRequest and retrieved an array of objects close to users location. What I want to do now is to get the average price from this fetch result. I have tried by retrieving NSNumber object like this

NSNumber *average = [resultArray valueForKeyPath:@"@avg.price"];
// always return 0

Tried with KVC by accessing the variable through my NSManagedObject class name like

NSNumber *average = [resultArray valueForKeyPath:@"[email protected]"];
// returned an error -[NSNull decimalValue]: unrecognized selector sent to instance

Couldn't get it to work with NSPredicate as well, fighting with this all day now and can't get my head around it. Any help would be much appreciated.

Upvotes: 1

Views: 309

Answers (1)

Cezar
Cezar

Reputation: 56362

You don't need to prepend the @avg operator with Product.

Use NSNumber *average = [resultArray valueForKeyPath:@"@avg.price"]; and you should be fine.

For more info on KVC Collection Operators, such as @avg, @sum and others, refer to this excellent NSHipster article.

Upvotes: 2

Related Questions