Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

luckylefty01

macrumors member
Original poster
Apr 8, 2008
32
0
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

Code:
---------------

@protocol MyClassProtocol

- (void)doFoo;

@optional 

- (void)barHappened

@end

---------------

@interface MyClass : NSObject {
  id<MyClassProtocol> delegate
}

@property (assign) id<classProtocol> delegate;

- (void)doBar;

@end

---------------

@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> {

}

@end

---------------

@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!
 
belated answer

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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.