In Objective-C, can I override the method in the subclass that the parent used to comply with the protocol?

An example is given below. If i installed

id<RandomProtocol> delegate = [[B alloc] init]; 

Will something be called from class A or class B?

hijras

 @protocol RandomProtocol -(NSString*)doingSomething; @end @interface A : NSObject <RandomProtocol> @end 

am

 #import "Ah" @implementation A - (NSString*) doingSomething { return @"Hey buddy."; } @end 

Bh

 #import "Ah" @interface B : A @end 

Bm

 #import "Bh" @implementation B - (NSString*)doingSomething { return @"Hey momma!"; } @end 
+4
source share
2 answers

To be more clear, an implementation of class B -doingSomething will be called instead of an implementation of class A simply because class B inherits from class A and never calls a super-implementation.

If you want to call the implementation from within B, you would add [super doingSomething] to the line inside the B -doingSomething method.

As mentioned in the previous answer, the fact that -doingSomething is declared in the protocol is completely irrelevant, since the protocols simply exist to provide compile-time information of what the class is capable of doing, for the developer’s own benefit.

+4
source

The implementation of Class B will be used whether it follows the protocol or not. The message "doneSomething" is sent to a class of type "B" because what you have allocated, and in class B, "doneSomething" is the first method that the runtime encounters when it moves through the class hierarchy.

+1
source

All Articles