当我调用函数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);
}
}发布于 2011-03-09 00:56:11
EXC_BAD_ACCESS通常意味着您有内存问题。
如果我不得不猜测的话,expressionForGraphView有时可能会返回垃圾。
https://stackoverflow.com/questions/5239165
复制相似问题