OBJ-C: Getting the minimum/maximum value in a NSMutableArray

Kevin picture Kevin · Feb 26, 2010 · Viewed 12.7k times · Source

I want to get the maximum and minimum values of a NSMutableArray so I can create a core-plot plotspace and graph based around those max and min values.

My code is as follows:

NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for (i=0; i<60; i++){
id x = [NSNumber numberWithFloat:i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_Max + 0.6];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}

self.dataForPlot = contentArray;

CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];

What do I fill in the blanks for xRange and yRange assignment if I want the graph to span only the space of what's specified in contentArray?

Answer

Barry Wark picture Barry Wark · Feb 26, 2010

In this case, you should use -[CPPlotSpace scaleToFitPlots:]. For more general calculations on array values, read on...

This is an ideal use for Key-Value coding and associated array operators. In your example,

float maxX = [[contentArray valueForKeyPath:@"@max.x"] floatValue];
float minY = [[contentArray valueForKeyPath:@"@min.x"] floatValue];

float maxY = [[contentArray valueForKeyPath:@"@max.y"] floatValue];
float minY = [[contentArray valueForKeyPath:@"@min.y"] floatValue];

The array operators call valueForKeyPath: on the contentArray which gives an array built by calling the same valueForKeyPath: on each member of the array with the key path to the right of the array operator (i.e. @min and @max). The orignal call then applies the given operator to the resulting array. You could easily define a category on NSArray to give you back a struct of min/max values:

typedef struct {
  float minX; 
  float minY;
  float maxX;
  float maxY;
} ArrayValueSpace;

@implementation NSArray (PlotSpaceAdditions)
- (ArrayValueSpace)psa_arrayValueSpace {
  ArrayValueSpace result;

  result.maxX = [[contentArray valueForKeyPath:@"@max.x"] floatValue];
  result.minX = [[contentArray valueForKeyPath:@"@min.x"] floatValue];

  result.maxY = [[contentArray valueForKeyPath:@"@max.y"] floatValue];
  result.minY = [[contentArray valueForKeyPath:@"@min.y"] floatValue];

  return result;
}