Call method for child class from parent class method (Objective-c 2.0)

I have experience with object-oriented programming, but for some reason this situation is unfamiliar. 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 in a child class from a method of the parent class? What happens if another child class does not implement the method g? Perhaps there is a better way to solve this, as an abstract method in the parent class A?

+5
source share
2 answers

The key must have a method in the parent class, which can be overridden 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

, . , :

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

: Yipe! Yipe! Yipe!

+11

g , . , , .

@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

.

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

.

+3

All Articles