[webkit-dev] Great function for Cocoa platform, bridge_cast
darin at apple.com
Tue Feb 15 09:43:58 PST 2022
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:
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.
Please consider this instead of writing things like (CFStringRef)keyNS.get() because it’s easier to see it’s correct.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the webkit-dev