I have this simple code in Swift:
override var bounds : CGRect {
didSet {
if (bounds != oldValue) {
var path = CGPathCreateMutable()
CGPathAddEllipseInRect(path, nil, bounds)
self.path = path
CGPathRelease(path)
}
}
}
It's supposed to draw a circle that fills the layer when the layer's bounds
changes.
This is ported from my old Objective-C code, which works fine:
- (void)setBounds:(CGRect)bounds
{
if (CGRectEqualToRect(self.bounds, bounds)) return;
super.bounds = bounds;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, nil, bounds);
self.path = path;
CGPathRelease(path);
}
However, the Swift code crashes with some segfault. If I don't release the path, it's fine. If I don't set self.path = path
, it's also fine (although nothing will show up, apparently). If both are present, it will crash.
I do think that a path created by CGPathCreateMutable()
needs to be released though.. and that seems to be the case for ObjC. Does anyone know why it doesn't work in Swift? Or did I do anything wrong?
Thanks!
You don't need to release CF objects in Swift. In your case, the CGPathCreateMutable()
returns a CGPath
object (not CGPathRef
) and is memory-managed just the same as any swift object. They explained this in the WWDC video Swift Interoperability In Depth
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With