我有兩個類,名爲Parent
和Child
,如下所示。 Parent
是Child
的超類我可以使用關鍵字super
從它的子類調用超類的方法。是否有可能從它的超類調用一個子類的方法?從其超類調用子類的方法
Child.h
#import <Foundation/Foundation.h>
#import "Parent.h"
@interface Child : Parent {
}
- (void) methodOfChild;
@end
Child.m
#import "Child.h"
@implementation Child
- (void) methodOfChild {
NSLog(@"I'm child");
}
@end
Parent.h:
#import <Foundation/Foundation.h>
@interface Parent : NSObject {
}
- (void) methodOfParent;
@end
Parent.m:
#import "Parent.h"
@implementation Parent
- (void) methodOfParent {
//How to call Child's methodOfChild here?
}
@end
導入 「Parent.h」 在應用程序委託的.m文件頭。
應用程序委託的application:didFinishLaunchingWithOptions:
方法..
Parent *parent = [ [Parent alloc] init];
[parent methodOfParent];
[parent release];
是的,這在技術上是可行的,但這種設計有味道。特別糟糕。超類不應該知道他們的子類。 – 2011-09-22 13:34:53
我想在從swift中調用的時候實現相同的功能,在這種層次結構中無法識別方法。任何人都可以告訴如何從第一次調用初始化Swift類時獲得相同的結果? – NaXir