关于iphone:CGContextRef损坏了吗?

CGContextRef getting corrupted?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
- (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的范围内绘制:

1
2
3
4
5
6
7
8
9
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);
    }
}

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

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