2010-07-20 40 views
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; 
+0

刚刚意识到我可以通过施放来排序! 感觉就像我不应该那样,有没有更好的方法来做到这一点? – baseten 2010-07-20 10:26:57

+0

让我们看看obj C代码而不是java代码 - 类模型是相同的 – Mark 2010-07-20 10:31:00

回答

1

对不起,因为我是编辑,我意识到,我是想圆做了错误的方式和分配AbstractLeafNode到菜单的问题,所以编译器完全警告是有道理的。将菜单分配给AbstractLeafNode时没有错误。

我一直盯着这太久了!