objective-cdelegatesprotocolsrespondstoselector

Method parameters, protocol methods, delegates and respondsToSelector calls


I have this kind of code :

MyClass.h

#import "MyOtherClass.h"

@interface MyClass : NSObject<SomeProtocol, MyOtherClassDelegate> {
...
}

MyClass.m

+ (void) doThis {
   [someObject doThisWithDelegate:self];  // someObject is MyOtherClass type
}

MyOtherClass.h :

@protocol MyOtherClassDelegate <NSObject>
@required
// Some methods
@end

- (void) doThisWithDelegate:(id<SomeOtherProtocol>)delegate;

MyOtherClass.m :

- (void) doThisWithDelegate:(id<SomeOtherProtocol>)delegate {
    if ([delegate respondsToSelector:@selector(myProtocolMethod:error:)]) do things;
}

Doing like this, I have the following warnings at compile time :

on the line [someObject doThisWithDelegate:self];

"Incompatible pointer types sending Class to parameter of type id<SomeOtherProtocol>"

on the method declaratéin in MyOtherClass.h :

"Passing argument to parameter 'delegate' here"

Before, I hadn't typed the id param (with id<SomeOtherProtocol>), it was just "alone" (id). I noticed that the test :

if ([delegate respondsToSelector:@selector(myProtocolMethod:error:)])

returned FALSE (but of course methods are implemented and declared in the delegate).

So I decided to try to force the id type to conform protocol that causes me that warning at compile time.

What is happening here ?
Why do I have this error, and why do the respondsToSelector do not return TRUE ?


Solution

  • Problem was that I've declare the doThis method as a class method and not instance method. So self is not valid when passed as a parameter.