Why is this code running on the simulator and crashing on a real device?
I have a very simple code that draws a circle. The code subclasses UIView
and runs fine on the Simulator (both for iOS 5.1 and 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
When I try to execute the code on an iPad2 running iOS 5.1.1 I get an error ( EXC_BAD_ACCESS(code=EXC_ARM_DA_ALIGN,address=0x31459241)
) on the CGContextAddPath( ctx, circle );
line.
I have not a clue of what the problem is. Can anyone point me in the right direction to solve this issue?
This is because the
CGPath
you are returning is owned by the autoreleasedUIBezierPath
created in thecirclePath
method. By the time you are adding the path object theUIBezierPath
has been released, so the returned pointer is pointing to invalid memory. You can fix the crash by returning theUIBezierPath
itself:Then draw using: