3

我正在使用以下内容来获取以下输出:

    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);
         }

     }
 }
 ];

我希望将数字相加以获得总数,然后除以计数以获得平均“评级”。

我试过这个,但显然语法不正确。我想我需要使用 NSArray 而不是“项目”:

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

谢谢你的帮助。

4

3 回答 3

12

您可以使用 KVC 获得平均值。一个例子

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

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

所以在你的情况下使用:

NSNumber *sum = [rateObjects valueForKeyPath:@"@sum.Rating"];
NSNumber *average = [rateObjects valueForKeyPath:@"@avg.Rating"];
于 2013-06-06T11:06:44.487 回答
3

尝试这个:

__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);
    }
}];
于 2013-06-06T11:04:06.033 回答
3

尝试这个:

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

在你的 for 循环之外

于 2013-06-06T11:06:43.673 回答