简体   繁体   中英

Releasing path with CGPathRelease causing BAD_ACCESS

I have a CGMutablePathRef property in a subclassed UIImageview. When I create a new path and assign it to the property, CGPathRelease causes an error when I call CGPathContainsPoint. IF I don't release the path the code works fine but there is a leak. How do I properly transfer ownership and release?

.h // UIImageView subclass
@property CGMutablePathRef pathHold;


.m
CGMutablePathRef myPath;
myPath = CGPathCreateMutable();
CGRect myRect2 = holderImageView.bounds;
float midX = CGRectGetMidX(myRect2);
float midY = CGRectGetMidY(myRect2);

CGAffineTransform t = 
CGAffineTransformConcat(
                        CGAffineTransformConcat(
                                                CGAffineTransformMakeTranslation(-midX, -midY), 
                                                     CGAffineTransformMakeScale(holderImageView.pathZone,holderImageView.pathZone)), 
                        CGAffineTransformMakeTranslation(midX, midY));
CGPathAddEllipseInRect(myPath, &t, myRect2);
CGPathCloseSubpath(myPath);

[holderImageView setPathHold:myPath];
CGPathRelease(myPath); // If path not released, works fine but leak.  
[self addSubview:holderImageView];
[holderImageView release];


.m
if(CGPathContainsPoint (self.pathHold, NULL, touchLocation, FALSE )) // This Causes error.

You're declaring your property without the (retain) attribute. It means, when you're assigning the path to this property, the runtime only does a pointer assignment and does not -retain your path, thus when you CGPathRelease() the path reference, it gets deallocated. So, you must declare the the property on the placeholder image class like this:

@property (retain) id pathHold;

and then assign it like this:

[holderImageView setPathHold:(id)myPath];

Please note that in the declaration I used 'id' as type. That's because almost any CoreGraphics and CoreFoundation type is in fact a valid Objective-C object, so this conversion (toll-free bridging) can be done and the type casting is only needed to avoid compiler warnings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM