Objective-C protocols that mimic "compilers" of "virtual functions" outputs?

In Objective-C, I would like to force derived classes to implement a given interface without providing a default implementation (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 am obviously missing something ...

I have defined a Parent class and have derived several child classes from the parent. All Child classes follow a protocol that requires myMethod to be implemented.

I would like to iterate over the Child instances, referencing them through the Parent superclass, calling myMethod on each one.

The compiler - not surprisingly - warns that the parent may not respond to myMethod.

All the evidence suggests that myMethod will in fact be called on each of the derived Child instances, but the fact that I am getting the warning is worrying me and suggests that I am not doing it correctly.

What am I missing?

thank

+2


source to share


2 answers


This does not mean that protocols are meant to be used. A protocol is an interface without implementation. If a class claims to conform to the protocol (presumably like your parent class), it needs to implement methods or you will get a warning. What you want to do is all the classes that actually implement the protocol, declare that they conform to it, and instead of referring to them by the name of that parent class, treat them like id<ProtocolNameHere>

. This states that they are entities conforming to this protocol.



+3


source


I notice a lot of interest in protocols and how they work. Unfortunately, there are many misleading guides on them.



Check out my tutorial Inheritance or Protocols? how protocols work, and when to use inheritance. Lots of code examples and a discussion of how protocols can be used in place of categories as Objective-C analogs of the abstract class of other languages ​​are included. Good luck with your development!

+2


source







All Articles