我最近开始了一个使用自动引用计数 (ARC) 的新项目。
当我分配 CALayer 的内容时:
UIView* view = ...
UIImage* image = ...
view.layer.contents = image.CGImage
我遇到了一个错误
Implicit conversion of a non-Objective-C pointer type 'CGImageRef' to 'id' is disallowed with ARC
只需将 CGImageRef
转换为 id
即可隐藏错误,但我想知道 ARC 是否仍能正常运行?
最佳答案
您真的应该看看 WWDC 2011 中的 ARC 视频。它们可以在开发者网站上找到并通过 iTunes 打开。特别是:
• Session 323 – Introducing Automatic Reference Counting
• Session 322 – Objective-C Advancements in Depth
此外,ARC 引用注释:
引用说明和视频都讨论了 Core Graphics(等)以及它们如何与 ARC 一起工作。
具体来说,请查看名为“管理免费桥接”
的部分In many Cocoa applications, you need to use Core Foundation-style objects, whether from the Core Foundation framework itself (such as CFArrayRef or CFMutableDictionaryRef) or from frameworks that adopt Core Foundation conventions such as Core Graphics (you might use types like CGColorSpaceRef and CGGradientRef).
The compiler does not automatically manage the lifetimes of Core Foundation objects; you must call CFRetain and CFRelease (or the corresponding type-specific variants) as dictated by the Core Foundation memory management rules (see Memory Management Programming Guide for Core Foundation).
If you cast between Objective-C and Core Foundation-style objects, you need to tell the compiler about the ownership semantics of the object using either a cast (defined in objc/runtime.h) or a Core Foundation-style macro (defined in NSObject.h): [...]
Jörg Jacobsen 对桥接选项也有很好的总结概述:Managing Toll-free Bridging in an ARC’ed Environment .
__bridge_retained (n.b.: only use it when casting from object pointer to C type pointer): I (the programmer) need to reference this object for some time in the dark world of C type pointers which is opaque to you, ARC. So please, please do not release this object while I still need it. I (the programmer) promise to release it myself (in the dark world) when I’m done with it
__bridge_transfer (n.b.: only use it when casting from C type pointer to object pointer): I (the programmer) hand over to you, ARC, an object that I own and that I am no longer interested in in the dark world of C type pointers that is opaque to you. Whenever you, ARC, are done with that object please release it yourself, because you know the right time and thus save me some work not having to do it myself.
__bridge: ARC, you keep balancing out your retains and releases as I keep balancing out mine in the dark world of C type pointers which is…. Whenever I need to hold on to an object in the dark world I will retain it myself and release it when appropriate. I don’t need any extra contract with you, ARC.
关于objective-c - ARC 是否与 Core Graphics 对象一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800174/