Inside -[ClassB foo]
, self.delegate
is declared as type id<MainProtocol>
– that is, it conforms to MainProtocol, but not necessarily to SubProtocol. As such, ClassB instances aren't sure that delegate
responds to -method2
. You can redeclare delegate
in ClassB as an object of type id<SubProtocol>
if you want to send -method2
to it.
Subclassing, protocols, and delegates - not calling
-
29-08-2022 - |
Question
I have 2 classes:
@protocol MainProtocol
-(void) method1;
@end
@interface ClassA : NSObject
@property id <MainProtocol> delegate;
@end
and
@protocol SubProtocol <MainProtocol>
-(void) method2
@end
@interface ClassB : ClassA
@end
@implementation ClassB
-(void) foo {
[self.delegate method1]; // works fine
[self.delegate method2]; // error
}
@end
I am not sure why I am unable to call method2
with self.delegate
. Is it because delegate
is declared in the parent class? If so, how do I localize delegate
in ClassB
?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow