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

流过昼夜 提交于 2019-12-05 06:54:24

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!