Can an ObjC class object conform to a protocol?

前端 未结 2 1007
挽巷
挽巷 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:25

    What you're doing now is correct as it will silence warnings which is your goal. You will be sending the class object messages defined in the protocol for instances which is a bit confusing, but the runtime doesn't care.

    Think about it this way: you want to set a delegate to an object that responds to the messages defined in the protocol. Your class does this, and your class is also an object. Therefore, you should treat your class like an object that conforms to that protocol. Therefore, what you've written is completely correct (based on what you're trying to do).

    One thing to note, though, is this class will not properly respond to conformsToProtocol:. This is generally okay for a delegate setup anyway (delegates don't usually check if the class conforms — they just check if it can respond to a selector).

    As a side note, one thing you can do syntactically is:

    Class variable = (Class)[self class];
    

    The difference here is that the compiler will use the class methods from the protocol instead of instance messages. This is not what you want in your case, though.

提交回复
热议问题