Objective-C - Overriding method in subclass

前端 未结 5 1405
借酒劲吻你
借酒劲吻你 2021-01-07 17:20

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):

相关标签:
5条回答
  • 2021-01-07 17:48

    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.

    0 讨论(0)
  • 2021-01-07 17:50

    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.

    0 讨论(0)
  • 2021-01-07 18:00

    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.

    0 讨论(0)
  • 2021-01-07 18:01
    -(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

    0 讨论(0)
  • 2021-01-07 18:02

    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];
    }
    
    0 讨论(0)
提交回复
热议问题