objective-c - ARC 和桥接铸件

使用 ARC,我不能再将 CGColorRef 转换为 id。我了解到我需要进行桥接类型转换。根据 clang docs :

A bridged cast is a C-style cast annotated with one of three keywords:

(__bridge T) op casts the operand to the destination type T. If T is a retainable object pointer type, then op must have a non-retainable pointer type. If T is a non-retainable pointer type, then op must have a retainable object pointer type. Otherwise the cast is ill-formed. There is no transfer of ownership, and ARC inserts no retain operations.

(__bridge_retained T) op casts the operand, which must have retainable object pointer type, to the destination type, which must be a non-retainable pointer type. ARC retains the value, subject to the usual optimizations on local values, and the recipient is responsible for balancing that +1.

(__bridge_transfer T) op casts the operand, which must have non-retainable pointer type, to the destination type, which must be a retainable object pointer type. ARC will release the value at the end of the enclosing full-expression, subject to the usual optimizations on local values.

These casts are required in order to transfer objects in and out of ARC control; see the rationale in the section on conversion of retainable object pointers.

Using a __bridge_retained or __bridge_transfer cast purely to convince ARC to emit an unbalanced retain or release, respectively, is poor form.

我会在什么样的情况下使用它们?

例如,CAGradientLayer 有一个 colors 属性,该属性接受 CGColorRef 数组。我的猜测是我应该在这里使用 __brige,但我应该(或不应该)的确切原因尚不清楚。

最佳答案

我同意描述令人困惑。由于我刚刚掌握了它们,所以我将尝试总结一下:

  • (__bridge_transfer <NSType>) op或者CFBridgingRelease(op)用于使用 CFTypeRef 的保留计数同时将其转移到ARC。这也可以表示为 id someObj = (__bridge <NSType>) op; CFRelease(op);

  • (__bridge_retained <CFType>) op或者CFBridgingRetain(op)用于递NSObject转移到CF-land,同时给它+1的保留计数。您应该处理 CFTypeRef您创建这种方式与处理 CFStringCreateCopy() 的结果相同.这也可以表示为 CFRetain((__bridge CFType)op); CFTypeRef someTypeRef = (__bridge CFType)op;

  • __bridge只是在指针域和 Objective-C 对象域之间转换。如果您不想使用上述转换,请使用此转换。

也许这会有所帮助。我自己,我更喜欢 CFBridging…宏在普通的 Actor 阵容中相当多。

https://stackoverflow.com/questions/7036350/

相关文章:

objective-c - Objective-C 可以打开 NSString 吗?

ios - 从另一个应用程序打开设置应用程序

ios - 获取 UIScrollView 滚动到顶部

ios - 如何将方法调用延迟 1 秒?

objective-c - 在 Objective-C 中,我为什么要检查 self = [supe

ios - 处理 NSDateFormatter 语言环境 "feature"的最佳方法是什么?

objective-c - 当前位置权限对话框消失得太快

objective-c - 如何判断 UITableView 何时完成 ReloadData?

objective-c - NSInvalidUnarchiveOperationException

objective-c - 如何摆脱 'undeclared selector' 警告