Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - Overriding method in subclass

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?

like image 474
Brett Avatar asked Jul 28 '11 11:07

Brett


People also ask

Does Objective C support method overriding?

Correct, objective-C does not support method overloading, so you have to use different method names.

Can subclass override methods?

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.

Which methods must be override in 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 should you override a method in a subclass?

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.


2 Answers

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]; } 
like image 156
Man of One Way Avatar answered Sep 20 '22 09:09

Man of One Way


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.

like image 43
Remy Vanherweghem Avatar answered Sep 18 '22 09:09

Remy Vanherweghem