0
我對Objective-C相當陌生,想知道是否有可能在分配對象時沒有收到編譯器警告時輸入對象作爲它們的超類型,或者是否有公認的方法實現相同的事情?Objective-C超類型多態性
我意識到這是ID是什麼類型的,但我有一個基類合成的具有特性,如果我嘗試使用ID我「的東西不是一個結構或聯合的成員‘X’的要求」得到的生成錯誤,大概是因爲動態類型可以將消息發送到對象,但不適用於訪問合成屬性。
例如在Java中我可能有:
public abstract class A {
public function doSomething() {
//some func
}
}
public class B extends A {
public function doSomething() {
//override some func
}
}
public class C extends A {
public function doSomething() {
//override some func
}
}
//and in my main class:
A objB = new B();
A objC = new C();
//the purpose of all of this is so I can then do:
A objHolder;
objHolder = objB;
objHolder.doSomething();
objHolder = objC;
objHolder.doSomething();
我目前在Objective-C的上述工作,但有一個編譯器警告: 「分配從不同的Objective-C型」
OK,這裏是Objective-C接口,如果需要,我可以添加實現。這是一個複合的模式:
//AbstractLeafNode
#import <Foundation/Foundation.h>
@interface AbstractLeafNode : NSObject {
NSString* title;
AbstractLeafNode* parent;
}
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) AbstractLeafNode* parent;
@end
//Page
#import "AbstractLeafNode.h"
@interface Page : AbstractLeafNode {
//there will be stuff here later!
}
@end
//Menu
#import "AbstractLeafNode.h"
@interface Menu : AbstractLeafNode {
NSMutableArray* aChildren;
}
- (void)addChild:(AbstractLeafNode *)node;
- (void)removeChild:(AbstractLeafNode *)node;
- (AbstractLeafNode *)getChildAtIndex:(NSUInteger)index;
- (AbstractLeafNode *)getLastChild;
- (NSMutableArray *)getTitles;
@end
// I'd then like to do something like (It works with a warning):
AbstractLeafNode* node;
Menu* menu = [[Menu alloc] init];
Page* page = [[Page alloc] init];
node = menu;
[node someMethod];
node = page;
[node someMethod];
// Because of the synthesized properties I can't do this:
id node;
// I can do this, but I suspect that if I wanted synthesized properties on the page or menu it would fail:
node = (AbstractLeafNode*)menu;
node = (AbstractLeadNode*)page;
剛剛意識到我可以通過施放來排序! 感覺就像我不應該那樣,有沒有更好的方法來做到這一點? – baseten 2010-07-20 10:26:57
讓我們看看obj C代碼而不是java代碼 - 類模型是相同的 – Mark 2010-07-20 10:31:00