Can an ObjC class object conform to a protocol?

前端 未结 2 1011
挽巷
挽巷 2021-02-02 12:48

Is there a way to indicate to the compiler that a class object conforms to a protocol?

As I understand, by creating +(void)foo class methods, an instanc

2条回答
  •  一向
    一向 (楼主)
    2021-02-02 13:41

    There is no Objective-C syntax to indicate that a metaclass conforms to a protocol.

    I think you can do it at runtime, by using class_addProtocol on the metaclass. But I haven't tried it.

    I guess you could also write a +conformsToProtocol: method on your class, and lie about your conformance. This could have unexpected side-effects, since there's already a +conformsToProtocol: on NSObject (in addition to -conformsToProtocol:).

    Neither of these will eliminate the need for a cast to shut the compiler up. Just use a singleton.

提交回复
热议问题