Skip to content

How to conform to virtual protocols #417

Open
@madsmtm

Description

@madsmtm

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-objc2Affects the `objc2`, `objc2-exception-helper` and/or `objc2-encode` cratesbugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions