views:

516

answers:

2

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

+1  A: 

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.

Chuck
Great, thanks. I guess I was unclear about one point: my parent class does _not_ implement the method, nor does it claim conformance to the protocol. These are, of course, as desired.What I was missing was the 'id<ProtocolName>' syntax--I was unaware of that. Thanks!
Joel
A: 

I'm noticing a lot of interest in protocols, and how they work. Unfortunately, there are a lot of misleading tutorials on them.

Check out my tutorial Inheritance or Protocols? on how protocols work, and when to use them instead of inheritance. Included is plenty of sample code, and a discussion of how protocols can be used rather than categories as Objective-C analogues to the abstract class of other languages. Good luck with your development!

Jonathan Sterling
@Jonathan: That link appears to be broken and I can't find the new location of the article.
Bill the Lizard
Moved to:http://jonsterling.github.com/2009/09/12/inheritance-or-protocols.html
robject
I just fixed the link in the answer. Thanks for noticing that!
Jonathan Sterling