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

让人想犯罪 __ 提交于 2019-12-07 03:22:48

问题


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?


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/8527343/calling-method-on-child-class-from-parent-class-method-objective-c-2-0

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