CGContextRef被破坏了吗?

时间:2011-03-08 22:28:54

标签: iphone objective-c ios

当我调用函数CGContextStrokePath(下面的代码中的最后一行)时,我的程序崩溃了。上下文可能以某种方式被破坏了吗? (当expression(NSArray)中有某些值时,它才会崩溃。它应该绘制expression中的任何内容的图形。例如,如果expression具有对象:x,cos(表示为字符串),它将绘制余弦曲线。这是代码:

- (double) yValueFromExpression:(id)anExpression atPosition:(double)xValue
{
    NSDictionary *aDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithDouble:xValue] forKey:@"%x"];
    return [CalculatorBrain evaluateExpression:anExpression usingVariableValues:aDictionary];
}

#define PRECISION 500

- (void)drawRect:(CGRect)rect 
{
    double scale = [self.delegate scaleForGraphView:self];
    id expression = [self.delegate expressionForGraphView:self];

    CGPoint origin; 
    origin.x = (self.bounds.origin.x + self.bounds.size.width) / 2;
    origin.y = (self.bounds.origin.y + self.bounds.size.height) / 2;

    [AxesDrawer drawAxesInRect:self.bounds originAtPoint:origin scale:scale];

    // -150/scale to 150/scale is the range of x values that axesDrawer (drawAxesInRect) displays.
    double leftMostXValue = -150 / scale;
    double rightMostXValue = 150 / scale;
    double increment = (rightMostXValue - leftMostXValue) / PRECISION;

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, self.bounds.origin.x, origin.y - 
                     [self yValueFromExpression:expression atPosition:leftMostXValue] * scale); 

    for (int i = 1; i <= PRECISION; ++i) {
        double currentXValue = leftMostXValue + i * increment;
        CGContextAddLineToPoint(context, self.bounds.origin.x + (self.bounds.size.width / PRECISION) * i, 
                            origin.y - [self yValueFromExpression:expression atPosition:currentXValue] * scale);
    }
    CGContextStrokePath(context);
}

这是调用CGContextStrokePath时收到的错误消息: Program received signal: “EXC_BAD_ACCESS”.

答案:我需要在CGContextAddLineToPoint()周围设置一个警卫,以确保它在rect的范围内绘制:

for (int i = 1; i <= PRECISION; ++i) {
    double currentXValue = leftMostXValue + i * increment;
    double xPoint = self.bounds.origin.x + (self.bounds.size.width / PRECISION) * i;
    double yPoint = origin.y - [self yValueFromExpression:expression atPosition:currentXValue] * scale;
    if (xPoint < (self.bounds.origin.x + self.bounds.size.width) && xPoint > 0 &&
        yPoint < (self.bounds.origin.y + self.bounds.size.height) && yPoint > 0) {
        CGContextAddLineToPoint(context, xPoint, yPoint);
    }
}

1 个答案:

答案 0 :(得分:1)

EXC_BAD_ACCESS通常意味着您有内存问题。

如果我不得不猜测,ExpressionForGraphView有时可能会返回垃圾。