[webkit-dev] Great function for Cocoa platform, bridge_cast

Ryosuke Niwa rniwa at webkit.org
Tue Feb 15 23:39:33 PST 2022


On Tue, Feb 15, 2022 at 9:44 AM Darin Adler via webkit-dev <
webkit-dev at lists.webkit.org> wrote:

> For those of you doing work with Objective-C on Cocoa platforms, I want to
> draw your attention to a great new idiom. Back in October, David Kilzer
> added bridge_cast, a type-safe set of functions that convert an Objective-C
> pointer to a Core Foundation pointer or vice versa, preserving types across
> the toll-free bridging boundary. It’s better than traditional non-WTF
> idioms where you use casts that look like “(__bridge id)” because you don’t
> have to write the type, and the correct corresponding type is chosen for
> you.
>
> When you have a CFStringRef and need to use it as an NSString key and
> value in an Objective-C dictionary, for example, the idiom would be:
>
>     bridge_cast(constantKey): bridge_cast(constantValue),
>
> Rather than the old:
>
>     (__bridge id)constantKey: (__bridge id)constantValue,
>
> It converts to NSString *, not id, which is better for many contexts, and
> good here, too. Since the function works in both directions, it will also
> turn an NSDictionary into a CFDictionaryRef. And it works on both raw
> pointers and on RetainPtr. I find it’s even more welcome to have something
> that can convert a RetainPtr<CFDictionaryRef> into RetainPtr<NSDictionary>
> without danger of getting the reference counting wrong, doing the right
> thing in both ARC and non-ARC source files, and optimizing the move cases
> appropriately.
>

Was there a particular reason we picked the same name for both conversions?
At first glance, the code would have been easier to read or understand if
it said to which direction we're doing the conversion: e.g.
toCF(constantKey), toNS(constantKey). We do this for WebCore/WebKit type
conversions.

- R. Niwa
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20220215/441ed49d/attachment.htm>


More information about the webkit-dev mailing list