Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method on child class from parent class method (Objective-c 2.0)

I have experience with object-oriented programming however this situation is unfamiliar for some reason. Consider the following Objective-c 2.0 code:

@interface A : NSObject
@end

@implementation A
- (void) f {
    [self g];
}
@end

@interface B : A
@end

@implementation B
- (void) g {
    NSLog(@"called g...");
}
@end

Is this the correct way to call a method on a child class from a method in the parent class? What happens if another child class doesn't implement method g? Perhaps there's a better way to solve this like an abstract method in the parent class A?

like image 706
SundayMonday Avatar asked Dec 15 '11 22:12

SundayMonday


People also ask

How do you call a method of parent class by an object of a child class in Java?

Use of super with methods This is used when we want to call the parent class method. So whenever a parent and child class have the same-named methods then to resolve ambiguity we use the super keyword.

Can we call the method of parent class by object of child class?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

Can a child class call base class methods?

A child class can access the data members of its specific base class, i.e., variables and methods. Within this guide, we will be discussing different ways to execute or call the base call function in C++.


2 Answers

The key is to have a method in the parent class that may be overriden in the child class.

@interface Dog : NSObject
- (void) bark;
@end

@implementation Dog
- (void) bark {
    NSLog(@"Ruff!");
}
@end

@interface Chihuahua : Dog
@end

@implementation Chihuahua
- (void) bark {
    NSLog(@"Yipe! Yipe! Yipe!");
}
@end

You see, your child class will override the parent method with its own implementation. You might see it used like this:

Dog *someDog = [Chihuahua alloc] init] autorelease];
[someDog bark];

Output: Yipe! Yipe! Yipe!

like image 71
Jeremy Avatar answered Nov 15 '22 07:11

Jeremy


You should implement g in the parent class, but make it do nothing. This way it can be called without error, but still can be overridden.

@interface A : NSObject
@end

@implementation A
- (void) f {
    [self g];
}
- (void) g {} // Does nothing in baseclass
@end

@interface B : A
@end

@implementation B
- (void) g {
    NSLog(@"called g...");
}
@end

Or you check for the method on the object before executing it.

if ([self respondsToSelector:@selector(g)]) {
  [self performSelector:@selector(g) withObject:nil];
}

But that can get pretty ugly.

like image 36
Alex Wayne Avatar answered Nov 15 '22 07:11

Alex Wayne