无法在Swift中释放CGPathCreateMutable创建的路径 [英] Cannot release path created by CGPathCreateMutable in Swift
问题描述
我在Swift中有以下简单代码:
重写var bounds:CGRect {
didSet {
if(bounds!= oldValue){
var path = CGPathCreateMutable()
CGPathAddEllipseInRect(path,nil,bounds)
self.path =路径
CGPathRelease(path)
}
}
}
应该绘制一个填充的圆
这是从我以前的Objective-C代码移植而来的,它工作正常:
-(void)setBounds:(CGRect)bounds
{
if(CGRectEqualToRect(self。界限,界限))返回;
super.bounds =界限;
CGMutablePathRef路径= CGPathCreateMutable();
CGPathAddEllipseInRect(path,nil,bounds);
self.path =路径;
CGPathRelease(path);
}
但是,Swift代码因某些段错误而崩溃。如果我不释放路径,那就很好。如果我未设置 self.path = path
,它也很好(尽管什么也不会出现)。如果两者都存在,则会崩溃。
我确实认为 CGPathCreateMutable()
创建的路径需要虽然被释放了..而ObjC似乎就是这种情况。有人知道为什么它不能在Swift中工作吗?还是我做错了什么?
谢谢!
您不需要在Swift中释放CF对象。在您的情况下, CGPathCreateMutable()
返回 CGPath
对象(而不是 CGPathRef
)并由内存管理,与任何swift对象相同。他们在WWDC视频 = a href = https://developer.apple.com/videos/play/wwdc2014/407/ rel = nofollow noreferrer>深度互操作性
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
这篇关于无法在Swift中释放CGPathCreateMutable创建的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!