Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot release path created by CGPathCreateMutable in Swift

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!

like image 277
danqing Avatar asked Jun 12 '14 04:06

danqing


1 Answers

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

like image 182
John Estropia Avatar answered Oct 01 '22 07:10

John Estropia