EXC_ARM_DA_ALIGN error when running on a device

2019-07-25 08:37发布

问题:

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?

回答1:

This is because the CGPath you are returning is owned by the autoreleased UIBezierPath created in the circlePath method. By the time you are adding the path object the UIBezierPath has been released, so the returned pointer is pointing to invalid memory. You can fix the crash by returning the UIBezierPath itself:

-(UIBezierPath *)circlePath {
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path addArcWithCenter:self.center radius:10.0 startAngle:0.0 endAngle:360.0 clockwise:YES];
    return path;
}

Then draw using:

CGContextAddPath( ctx, circle.CGPath );