Core plot data source returns huge number

90 Views Asked by At

I am implementing a scatter graph in core plot and one of the data source methods is returning a huge number. Here is the method:

- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return [self.values count];
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    switch (fieldEnum) {
        case CPTScatterPlotFieldX:
            if (index < [self.practices count]) {
                return [NSNumber numberWithUnsignedInteger:index];
            }
            break;

        case CPTScatterPlotFieldY:

            if ([plot.identifier isEqual:@"Practices"]) {
                return self.values[index];
            }
            break;
    }
    return [NSDecimalNumber zero];
}

Here is the population of self.values:

    NSMutableArray *value = [[NSMutableArray alloc] initWithCapacity:200];

    for (int i = 200; i > 0; i--) {
        NSInteger randomNumber = arc4random() % 200;
        [value addObject:[NSNumber numberWithInt:randomNumber]];
    }

    NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    [value sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];

    self.values = [value copy];

The graph is crashing when it calls: return self.values[index];. When I try to debug the application I am finding that the index passed in is very large.

Here is a picture of that variable. It's the one called index:

enter image description here

I am trying to figure out why this number is so large. Everything seems to be similar to other graphs I have implemented. However this seems to be throwing in a large number.

1

There are 1 best solutions below

0
On

I have managed to find a work around to get this to work. My original code did not have a check in CPTScatterPlotFieldY to see if index < [self.values count].

switch (fieldEnum) {
    case CPTScatterPlotFieldX:
        if (index < [self.values count]) {
            return [NSNumber numberWithUnsignedInteger:index];
        }
        break;

    case CPTScatterPlotFieldY:

        if ([plot.identifier isEqual:@"gpPractices"] && index < [self.values count]) {
            return self.values[index];
        }
        break;
}
return [NSDecimalNumber zero];

By adding this check it only tries to access the self.values array if the index is less than the number of objects in the array.