In Objective-C, I’d like to force derived classes to implement a given interface without providing a default implementation (an implementation in the parent class).
I understand that Protocols can be used for this, and I believe I understand how to use Protocols, but I’m apparently missing something…
I have defined class Parent, and derived several Child classes from parent.
All Child classes conform to a protocol which requires implementation of myMethod.
I’d like to iterate through Child instances, referring to them via the superclass Parent, calling myMethod on each.
The compiler–not surprisingly–warns that Parent may not respond to myMethod.
All evidence suggests that myMethod will in fact be called for each of the derived Child instances, but the fact that I get a warning makes me uneasy, and suggests that I’m not implementing this correctly.
What am I missing?
Thanks
This isn’t how protocols are meant to be used. A protocol is an interface without an implementation. If a class claims to conform to a protocol (as your parent class apparently does), it needs to implement the methods or you’ll get a warning. What you want to do is have all the classes that actually implement the protocol declare that they conform to it, and rather than refer to them by this parent class name, refer to them as
id<ProtocolNameHere>. This declares that they are objects conforming to that protocol.