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
?
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.
By writing:
-(void)methodName {
[super methodName];
}
You tell the compiler: When executing methodName of Class B, call methodName of its superclass (Class A). So if you want Class B to do something different you have to write code that results in a different behavior. Like this:
-(void)methodName {
NSLog(@"Hello, world!");
}
Now by calling methodName of Class B "Hello, world!" will be printed on the console.
-(void)methodName {
[super methodName];
}
Wanna call methodName (in ClassB), just remove [super method] then you can fire it. Cause super is call back to ClassA
Although this question is too old, but there are sill some learners as every expert was, The following is quoted from Apple documentation. "The new method must have the same return type and take the same number and type of parameters as the method you are overriding." full answer can be found in Apple method overriding documentation Hope this helps someone.
精彩评论