I am having some trouble figuring out hour to accurately override a method in one of my subclasses.
I have subclass (ClassB) of another customclass (ClassA):
@interface ClassB : ClassA { }
and within ClassA
, there is a method called:
-(void)methodName;
which fires correctly.
However, I need this method to fire in ClassB
.
I've tried implementing (in ClassB
):
-(void)methodName { [super methodName]; }
but it still won't fire in ClassB
.
How can I override methodName so that it will fire in ClassB
?
Correct, objective-C does not support method overloading, so you have to use different method names.
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
Subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. Writing Abstract Classes and Methods discusses abstract classes and methods in detail.
When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
You just add your custom code in methodName in classB :
- (void)methodName { // custom code // call through to parent class implementation, if you want [super methodName]; }
First, make sure your init method creates a ClassB object and not a ClassA (or something else) object.
Then, if you want to create a completely different classB (void)methodName: method than the one found in classA, this is the way to go:
Super is the superclass. By calling [super methodName] you're asking ClassA to execute it's own methodName. If you want to completely override methodName from classA, just don't call super.
So, basically, in your classB's implementation of methodName:
-(void)methodName { // Remove [super methodName] // Insert the code you want for methodName in ClassB }
Feel free to read Messages to self and super in Apple's The Objective-C Programming Language document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With