objc2 icon indicating copy to clipboard operation
objc2 copied to clipboard

How to conform to virtual protocols

Open madsmtm opened this issue 1 year ago • 1 comments

Some protocols like UIApplicationDelegate are not registered with the runtime until the compiler has seen a @protocol(UIApplicationDelegate), or the protocol is implemented by a concrete class (details).

This leads to code that tries to declare a class that implements the protocol to not actually do so at runtime:

declare_class!(
    struct AppDelegate;
    
    unsafe impl ClassType for AppDelegate {
        type Super = NSObject;
        const NAME: &'static str = "MyApplicationDelegate";
    }
    
    unsafe impl UIApplicationDelegate for AppDelegate {}
);

let obj = AppDelegate::new();

// In ObjC, this fails:
[obj conformsToProtocol: objc_getProtocol("UIApplicationDelegate")]

Implementation-wise, clang emits static shenanigans similar to what it does when sending messages or declaring classes such that the protocol is known to the dynamic linker and the objc runtime startup code.

We could perhaps do something like this as well, either by emitting the statics (hard and brittle), or by using ProtocolBuilder (will lead to lots of dead code, e.g. some protocols like NSCopying is always available since there are classes in Foundation that implement it).

madsmtm avatar Feb 02 '23 09:02 madsmtm