【发布时间】:2011-08-16 22:36:24
【问题描述】:
我经常发现我知道基类的某个属性将始终是子类中的某个类型。例如,在下面的示例中,属性obj 在 Derived 中将始终是一个 NSString 对象。但是,我需要这个属性是 Base 类中更通用的 id 类型。
@interface Base
@property (strong, nonatomic) id obj;
@end
@implementation Base
//@synthesize obj = obj_;
@dynamic obj;
@end
@interface Derived : Base
@property (strong, nonatomic) NSString *obj;
@end
@implementation Derived
@synthesize obj = obj_;
@end
这段代码正确吗?我担心@synthesize 出现两次。这是创建两个属性,还是 Derived 中的 @synthesize 声明覆盖 Base 中的那个?
编辑:在 Base 中将 @synthesize 更改为 @dynamic 更有意义。
编辑:这需要 iOS SDK 5。
【问题讨论】:
-
出于好奇,如果您获取 Derived 的实例,将其强制转换回 Base,然后将非字符串对象分配给该属性,您期望会发生什么?换句话说,类似于
((Base *)myDerived).obj = [NSNumber numberWithInt:3]。 -
Re 上面的“出于好奇”,这相当于说,“如果您将 Derived 的实例转换为
(UICollectionViewController *)myDerived然后......键入它不是,不要期望好的结果。这包括不能将子类视为其超类。 -
@KevinBallard 感谢您的评论。简明扼要。
标签: objective-c