如何在父类中调用子类的方法
测试代码:
#import "ViewController.h"
#import "SubClass.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
BaseClass *sub = [[SubClass alloc] init];
[sub baseFun];
}
@end
BaseClass文件:
#import <Foundation/Foundation.h>
@interface BaseClass : NSObject
- (void)baseFun;
@end
#import "BaseClass.h"
#import <objc/message.h>
@implementation BaseClass
- (void)baseFun {
// 1、使用runtime进行消息发送
objc_msgSend(self, @selector(subFun));
// 2、在父类中将方法写出来,只是为了能编译通过,最终调用的时候还是会调用子类的subFun方法
[self subFun];
}
- (void)subFun{}
@end
BaseClass文件:
#import "BaseClass.h"
@interface SubClass : BaseClass
@end
#import "SubClass.h"
@implementation SubClass
- (void)subFun {
NSLog(@"子类SubClass被调用了");
}
@end
网友评论