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.
Method parameters, protocol methods, delegates and respondsToSelector calls
-
31-05-2022 - |
Pregunta
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 ?
Solución 3
Otros consejos
If you want to call respondsToSelector:
on a property with a type of id<SomeProtocol>
then make sure your protocol conforms to the NSObject
protocol.
Example:
@protocol SomeOtherProtocol <NSObject>
// methods
@end
This will then allow you to do:
if ([self.delegate respondsToSelector:@selector(myProtocolMethod:error:)]) {
}
This assumes delegate
is defined as:
@property (nonatomic, weak) id<SomeOtherProtocol> delegate;
First make sure you conform to , respondsToSelector is part of NSObject.
Second I would check that i had effectively set the delegate property.
This line :
if ([self.delegate respondsToSelector:@selector(myProtocolMethod:error:)])
should work, since the property delegate is pointing to an object that should have myProtocolMethod:error: ....
I would probably debug with a breakpoint or a test on a setter for the delegate :
-(void)setDelegate:(id)delegate
{
NSLog("We are setting a delegate!: %@", [delegate description]);
_delegate = delegate;
}
If when you run your app, you see the "We setting...." after you do your if line or if you don't see it at all, then you know where your issue is.