Cannot release path created by CGPathCreateMutable in Swift

☆樱花仙子☆ 提交于 2019-12-10 16:28:37

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/24176481/cannot-release-path-created-by-cgpathcreatemutable-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!