Child class calls a method of the parent class

Danegraphics picture Danegraphics · May 29, 2011 · Viewed 9k times · Source

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)

Answer

Simon Whitaker picture Simon Whitaker · May 29, 2011

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?