Do you need to release CGContextRef in Swift?

回眸只為那壹抹淺笑 提交于 2019-12-03 19:23:01

问题


I've created a context using CGBitmapContextCreate. Do I need to release it using CGContextRelease? I know the answer is yes in Objective-C, but how about in Swift?

Thanks!


回答1:


CFTypes are automatically managed unless explicitly specified as Unmanaged.
According to the documentation. 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.

Unmanaged types will have the type signature

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

CGBitmapContextCreate has the type signature

func CGBitmapContextCreate(...) -> CGContext!

Hence its managed automatically by swift.




回答2:


No, you don't need to call CGContextRelease. In fact, trying to gives you this error:

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

CGContext instances are automatically memory managed in Swift. You can tell from the function signature:

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

A return value you would need to release yourself would look like:

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


来源:https://stackoverflow.com/questions/27872822/do-you-need-to-release-cgcontextref-in-swift

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