Reputation: 193
I am currently attempting to obtain an average result (on button press) of an array using the following code for testing purposes:
- (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];
}
However, when I run the application and press the 'calculate' button the debugging console returns:
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.'
Does anybody know what the issue might be here?
Upvotes: 0
Views: 308
Reputation: 4656
Use self instead of amount:
NSNumber *avg = [resultsArray valueForKeyPath:@"@avg.self"];
If the array contained objects/dictionaries and you wanted to get average of a particular property/key then you could place its name instead like amount etc but here they are just NSNumbers
so self
is sufficient!
Upvotes: 4
Reputation: 965
You can also do this for sorting the array. if you have not only number on your array. This kind like more manual
float total;
total = 0;
int totalCount = 0;
for(NSNumber *value in myArray){
total+=[value floatValue];
count ++;
}
float average = total/count;
Upvotes: 0
Reputation: 125007
Try this instead:
NSNumber *avg = [resultsArray valueForKeyPath:@"@avg.self"];
According to the error, the objects in the array don't respond to the amount
selector. Makes sense, they're NSNumber
objects. Your existing code would work if you had an array of objects (dictionaries, for example) that all respond to the key amount
.
Upvotes: 1