获得NSMutableArray的平均值

时间:2014-08-11 14:02:12

标签: ios objective-c nsmutablearray average

我目前正在尝试使用以下代码获取阵列的平均结果(按下按钮)以进行测试:

- (IBAction)calculate:(id)sender {

    NSString *number1result = _number1.text;
    NSInteger number1int = [number1result integerValue];
    NSString *number2result = _number2.text;
    NSInteger number2int = [number2result integerValue];
    NSString *number3result = _number3.text;
    NSInteger number3int = [number3result integerValue];

    NSMutableArray *resultsArray = [[NSMutableArray alloc]init];
    [resultsArray addObject:[NSNumber numberWithFloat:number1int]];
    [resultsArray addObject:[NSNumber numberWithFloat:number2int]];
    [resultsArray addObject:[NSNumber numberWithFloat:number3int]];

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

    _arrayOutput.text = [NSString stringWithFormat:@"%@",avg];

}

但是,当我运行应用程序并按下“计算”按钮时,调试控制台将返回:

2014-08-11 15:00:39.033 arrayTest[15259:60b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFNumber 0x109349c60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key amount.'

有人知道这里可能出现的问题吗?

3 个答案:

答案 0 :(得分:4)

使用自我代替金额

NSNumber *avg = [resultsArray valueForKeyPath:@"@avg.self"];

如果数组包含对象/字典,并且您希望获得特定属性/键的平均值,那么您可以将其名称替换为金额等,但这里它们只是NSNumbers所以self就足够了!

答案 1 :(得分:1)

请改为尝试:

NSNumber *avg = [resultsArray valueForKeyPath:@"@avg.self"];

根据错误,数组中的对象不会响应amount选择器。有道理,他们是NSNumber个对象。如果您有一组对象(例如字典)都响应密钥amount,那么现有代码就可以工作。

答案 2 :(得分:0)

您也可以对数组进行排序。如果您的阵列上不仅有数字。这种更像手动

    float total;
    total = 0;
    int totalCount = 0;
    for(NSNumber *value in myArray){
        total+=[value floatValue];
        count ++;
    }

    float average = total/count;