Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In addition to katzenhut's suggestion of manually calculating the average, you can use KVC collection operators, too, e.g.:</p> <pre><code>NSArray *array = @[@10, @25, @30]; NSNumber *average = [array valueForKeyPath:@"@avg.self"]; </code></pre> <p>Or, if dealing with objects, for example a "Product" model object with this interface:</p> <pre><code>@interface Product : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic) double price; - (id)initWithName:(NSString *)name price:(double)price; // the corresponding implementation should be obvious, so I'll not include it in this code snippet @end </code></pre> <p>You could then do:</p> <pre><code>NSMutableArray *products = [NSMutableArray array]; [products addObject:[[Product alloc] initWithName:@"item A" price:1010.0]]; [products addObject:[[Product alloc] initWithName:@"item B" price:1025.0]]; [products addObject:[[Product alloc] initWithName:@"item C" price:1030.0]]; NSNumber *average = [products valueForKeyPath:@"@avg.price"]; </code></pre> <hr> <p>If you want to take the results and populate a label with the results, you might do something like:</p> <pre><code>NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterDecimalStyle; formatter.maximumFractionDigits = 2; // two decimal places? self.averageLabel.text = [formatter stringFromNumber:average]; </code></pre> <p>The advantage of <code>NSNumberFormatter</code> over <code>stringWithFormat</code> is that you have greater control over the string representation of the number, e.g. it can observe localization, employ thousandths separators, etc.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload