使用 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 typeT
. IfT
is a retainable object pointer type, thenop
must have a non-retainable pointer type. IfT
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/