3

I'm using the following to get an output of:

    2013-06-06 11:44:27.325 [2570:907] Rating: 0
    2013-06-06 11:44:27.326 [2570:907] Rating: 2
    2013-06-06 11:44:27.327 [2570:907] Rating: 3 


[rateQuery findObjectsInBackgroundWithBlock:^(NSArray *rateObjects, NSError *error)
 {
     if( !error )
     {
         NSLog(@"rateobject %@", rateObjects);

         for (id item in rateObjects) {

             int ratingVal = [[item objectForKey:@"Rating"] intValue];
             NSLog(@"Rating: %d", ratingVal);
         }

     }
 }
 ];

I'm looking to add the numbers to get a total and then divide by a count to get an average "rating".

I tried this, but obviously the syntax is incorrect. I think I need to use an NSArray instead of "item":

NSNumber *sum=[[item objectForKey:@"Rating"] valueForKeyPath:@"@sum.floatValue"];
                 NSLog(@"Rating Sum: %@", sum);

thanks for any help.

hanumanDev
  • 6,592
  • 11
  • 82
  • 146

3 Answers3

12

You can get the average using KVC. An example

NSArray *objects = @[
@{ @"Rating": @4 },
@{ @"Rating": @6 },
@{ @"Rating": @10 }
];

NSLog(@"Average: %@", [objects valueForKeyPath:@"@avg.Rating"]);
// results in "Average: 6.666666"

So in your case use:

NSNumber *sum = [rateObjects valueForKeyPath:@"@sum.Rating"];
NSNumber *average = [rateObjects valueForKeyPath:@"@avg.Rating"];
Joris Kluivers
  • 11,894
  • 2
  • 48
  • 47
3

try this:

__block float sum = 0;
[rateQuery findObjectsInBackgroundWithBlock:^(NSArray *rateObjects, NSError *error)  {
    if( !error )      {
        NSLog(@"rateobject %@", rateObjects);

        for (id item in rateObjects) {
            sum = sum + [[item objectForKey:@"Rating"] intValue];
            int ratingVal = [[item objectForKey:@"Rating"] intValue];
            NSLog(@"Rating: %d", ratingVal);
        }
        NSLog(@"Sum: %f", sum);
        NSLog(@"Average: %f", sum/rateObjects.count);
    }
}];
DharaParekh
  • 1,730
  • 1
  • 10
  • 17
  • thanks! with this line sum = sum + [[item objectForKey:@"Rating"] intValue]; I get an error stating that "variable is not assignable (missing __block specific type specifier. Do I have to declare float sum in the .h file? thanks – hanumanDev Jun 06 '13 at 11:08
3

Try this:

NSNumber *sum = [rateObjects valueForKeyPath:@"@sum.Rating"];

outside of your for-loop

gasparuff
  • 2,295
  • 29
  • 48