Objective-C超类型多态性

时间:2010-07-20 10:25:02

标签: objective-c polymorphism dynamic-typing

我是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类型分配”

好的,这是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;

1 个答案:

答案 0 :(得分:1)

很抱歉,当我编辑这个问题时,我意识到我试图以错误的方式进行操作并将AbstractLeafNode分配给菜单,因此编译器警告完全有意义。将菜单分配给AbstractLeafNode时没有错误。

我已经盯着这个太久了!