您需要在 Swift 中释放 CGContextRef 吗?

Do you need to release CGContextRef in Swift?

我使用 CGBitmapContextCreate 创建了一个上下文。我需要使用 CGContextRelease 来发布它吗?我知道在 Objective-C 中答案是肯定的,但是在 Swift 中呢?

谢谢!

CFTypes 是自动管理的,除非明确指定为非托管。
根据文档。 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

Core Foundation objects returned from annotated APIs are automatically memory managed in Swift—you do not need to invoke the CFRetain, CFRelease, or CFAutorelease functions yourself. If you return Core Foundation objects from your own C functions and Objective-C methods, annotate them with either CF_RETURNS_RETAINED or CF_RETURNS_NOT_RETAINED. The compiler automatically inserts memory management calls when it compiles Swift code that invokes these APIs. If you use only annotated APIs that do not indirectly return Core Foundation objects, you can skip the rest of this section. Otherwise, continue on to learn about working with unmanaged Core Foundation objects.

When Swift imports APIs that have not been annotated, the compiler cannot automatically memory manage the returned Core Foundation objects. Swift wraps these returned Core Foundation objects in an Unmanaged structure.

非托管类型将具有类型签名

func StringByAddingTwoStrings(CFString!, CFString!) -> Unmanaged<CFString>!

CGBitmapContextCreate 具有类型签名

func CGBitmapContextCreate(...) -> CGContext!

因此它由 swift 自动管理。

不,您不需要致电 CGContextRelease。事实上,试图给你这个错误:

'CGContextRelease' is unavailable: Core Foundation objects are automatically memory managed

CGContext 个实例在 Swift 中自动进行内存管理。从函数签名可以看出:

func CGBitmapContextCreate(/* several parameters */) -> CGContext!

您需要释放自己的 return 值如下所示:

func CGBitmapContextCreate(/* several parameters */) -> Unmanaged<CGContext>!