【发布时间】:2011-06-19 22:10:34
【问题描述】:
有A类:
@interface ClassA : NSObject {
}
@property (nonatomic, assign) id prop1;
@end
@implementation
@synthesize prop1;
@end
然后我有子类
@interface ClassB : ClassA {
}
@end
@implementation
- (id)init {
self = [super init];
if (self) {
}
return self;
}
//This is infinite loop
- (void) setProp1:(id)aProp
{
self.prop1 = aProp;
}
@end
这是无限循环,因为 ClassB 中的 setProp1 从 ClassB 中调用 [ClassB setProp1:val]。
我已经尝试过调用 [super setProp1] 但是这个
如何覆盖 @property 并在覆盖的 setter 中赋值?假设我不能修改 ClassA。
【问题讨论】:
-
“我已经尝试调用 [super setProp1] 但是这个”...?出了什么问题?
super在这里是正确的。 -
super 仅在 super 中更改值。 self.prop1 为 null 并且 super.prop1 有值。 self->prop1 解决问题(正如 Sherm 建议的那样)
-
self.prop1 和 super.prop1 绝对应该不返回不同的值。你是否也覆盖了 getter 方法?
-
是的,我这样做了,它从这个设置器返回“aProp”。
-
getter 的超类实现不应该已经这样做了吗?
标签: objective-c ios overriding subclass