View Full Version : Delegates, protocols, and optional methods

Jul 20, 2008, 05:56 PM
Hey everybody, I want to make a create a delegate protocol for one of my classes and I have a quick question. I'm trying to make a couple of the methods optional, but I've not found a really great way to get rid of the warning I'm getting.

Here's what I'm doing now


@protocol MyClassProtocol

- (void)doFoo;


- (void)barHappened



@interface MyClass : NSObject {
id<MyClassProtocol> delegate

@property (assign) id<classProtocol> delegate;

- (void)doBar;



@implementation MyClass

- (void)doBar {

// Do Bar

if ([delegate responseToSelector:@selector(barHappened)]) {
[delegate barHappened];

// Some other method telling delegate to doFoo


#import "MyClass.h" // For protocol
@interface TheDelegate : NSObject <MyClassProtocol> {




@implementation TheDelegate

- (id)init {
//init MyClass here and set self as delegate

- (void)dealloc {
// Release MyClass

//Delegate method for MyClass
- (void)doFoo {
// Do fooey stuff

//Optional delegate method for MyClass
- (void)barHappened {
// Tell something to do something about this most wonderful turn of events

The basic problem here is that of course I get a warning that delegate may not respond to respondsToSelector:, because that method is defined in NSObject and delegate is defined as an id conforming to the MyClassDelegate protocol.

Is there an easy way to let the compiler know that delegate will respond?

I guess I could change delegate from an id to an NSObject, but that seems like a bit of a pain. It seems like there should be an easier way.

Adding a dummy responds to selector method to the protocol seems like a bad idea.

Of course I could also just ignore the warning, but I don't want to. It's the only warning I'm getting:P.

I feel like I'm missing something easy.

Thanks for any help!

Jun 1, 2010, 09:12 PM
Two issues:
your protocol should be
@protocol MyClassProtocol <NSObject>

...and the warning is really because you are calling responseToSelector: not respondsToSelector:

You have figured that out by now, but I was just looking for an answer to this very question, found this, found the answer elsewhere, so now I'll post it here for the next seeker.