为什么此代码在模拟器上运行并在真实设备上崩溃?
我有一个非常简单的代码,它绘制了一个圆圈。代码子类UIView
并在Simulator上运行良好(适用于iOS 5.1和iOS 6.0)。
Circle.h
#import <UIKit/UIKit.h>
@interface Circle : UIView
@end
Circle.m
#import "Circle.h"
@implementation Circle
-(CGPathRef) circlePath{
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:self.center radius:10.0 startAngle:0.0 endAngle:360.0 clockwise:YES];
return path.CGPath;
}
- (void)drawRect:(CGRect)rect
{
CGPathRef circle = [self circlePath];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddPath( ctx, circle );
CGContextStrokePath(ctx);
}
@end
当我尝试在运行iOS 5.1.1的iPad2上执行代码时,我在EXC_BAD_ACCESS(code=EXC_ARM_DA_ALIGN,address=0x31459241)
行上收到错误(CGContextAddPath( ctx, circle );
)。
我不知道问题是什么。有人能指出我正确的方向来解决这个问题吗?
答案 0 :(得分:0)
这是因为您要返回的CGPath
归UIBezierPath
方法中创建的自动释放的circlePath
所有。当您添加路径对象时UIBezierPath
已被释放,因此返回的指针指向无效的内存。您可以通过返回UIBezierPath
本身来修复崩溃:
-(UIBezierPath *)circlePath {
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:self.center radius:10.0 startAngle:0.0 endAngle:360.0 clockwise:YES];
return path;
}
然后使用:
绘制CGContextAddPath( ctx, circle.CGPath );