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

- (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.'


有人知道问题可能在这里吗?

最佳答案

用self代替数量:

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


如果数组包含对象/字典,并且您想获取特定属性/键的平均值,则可以放置其名称,而不是数量等,但是这里它们只是NSNumbers,因此self就足够了!

关于ios - 获得NSMutableArray的平均值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25245152/

10-10 17:20