我对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 中进行了上述工作,但有一个编译器警告:“assignment from distinct Objective-C type”
好的,这是 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;