2

In objective-C I want to have a child class call or invoke a parent's method. As in the parent has allocated the child and the child does something that would invoke a parent method. like so:

//in the parent class
childObject *newChild = [[childClass alloc] init];
[newChild doStuff];

//in the child class
-(void)doStuff {
    if (something happened) {
        [parent respond];
    }
}

How could I go about doing this? (if you could explain thoroughly I would appreciate it)

Danegraphics
  • 447
  • 1
  • 7
  • 21
  • Possible duplicate of [HOWTO access the method declared in the parent class?](http://stackoverflow.com/questions/5063484/howto-access-the-method-declared-in-the-parent-class) –  Nov 29 '16 at 01:31

2 Answers2

7

You can use a delegate for this: have childClass define a delegate protocol and a delegate property that conforms to that protocol. Then your example would change to something like this:

// in the parent class
childObject *newChild = [[childClass alloc] init];
newChild.delegate = self;
[newChild doStuff];

// in the child class
-(void)doStuff {
    if (something happened) {
        [self.delegate respond];
    }
}

There's an example of how to declare and use a delegate protocol here: How do I set up a simple delegate to communicate between two view controllers?

Community
  • 1
  • 1
Simon Whitaker
  • 20,506
  • 4
  • 62
  • 79
4

There's not really a lot to explain.

For use in this situation you have the keyword super, which is a lot like self, except that it refers to what self had been had it been a member of its own immediate superclass:

// in the child class
- (void)doStuff {
  if (something happened) {
    [super respond];
  }
}
Williham Totland
  • 28,471
  • 6
  • 52
  • 68
  • 1
    That's not right - `super` refers to an object's superclass, not the object that instantiated it. – Simon Whitaker May 29 '11 at 18:26
  • 1
    @Simon Whitaker: He is asking about a *child class*. Not the correct terminology, sure, but it's a leap to suggest he wants to talk to the instantiating object. – Williham Totland May 29 '11 at 18:33
  • 2
    Not really - that's exactly what he specifies in his question. "The parent has allocated the child and the child does something that would invoke a parent method." Agree that the terminology's poorly used though. – Simon Whitaker May 29 '11 at 18:39
  • 1
    @Simon Whitaker: That sentence could equally well refer to subclassing and delegation. – Williham Totland May 29 '11 at 19:03
  • 1
    Actually I want the instantiating object. I don't know what the "correct" terminology would be for an object that allocates another. – Danegraphics May 29 '11 at 19:27
  • 1
    This answer is great if you just foget `super` keyword in Obj-C. I found this question/answer in Google, and this is what I actually looked for. Thank you. – Mike Keskinov Jul 27 '15 at 21:33