我在 Objective-C 中有一个抽象接口(interface),其中每个子类都需要设置一个属性,然后在 init
结束时对该属性执行完全相同的操作。我试图用这样的方式避免重复代码:
接口(interface)文件
@interface Shape : NSObject
@property (nonatomic) PropertyType *prop;
- (id)init;
- (void)initProperty;
@end
执行文件
@implementation Shape
- (id)init
{
if(self = [super init]) {
[self initProperty];
[prop doSomething];
}
return self;
}
- (void)initProperty
{
}
@end
我的问题是每个子类都需要一组不同的参数传递给 initProperty
才能正确实现该方法:
@implementation Rectangle
- (void)initPropertyWithRect:(CGRect)rect
{
prop = [RectangleStuff rectangleWithRect:rect];
}
@end
@implementation Circle
- (void)initPropertyWithRadius:(CGFloat)radius
{
prop = [CircleStuff circleWithRadius:radius];
}
@end
是否有一种干净的方法来完成我在 Objective-C 中尝试做的事情?到目前为止,我的选择似乎是:
- 创建一个“属性包”,然后传递一个
NSDictionary
。 - 在每个子类中复制
[property doSomething];
代码。 - 以某种方式将工厂对象传递给 init,并让工厂对象创建
prop
。这种方法似乎是最干净的,但我需要工厂对象以某种方式将矩形和/或半径保持为内部状态,这对我来说似乎并不干净。
有什么想法吗?
最佳答案
我可能会选择#2(为了简单起见)。如果属性只设置一次 (在子类 init 方法中),您可以覆盖 父类(super class),并在那里做额外的事情。
未经测试的代码:
- (void)setProp:(PropertyType *)prop
{
_prop = prop; // (Assuming ARC)
[_prop doSomething];
}
关于ios - 在 init 中操作由 Objective-C 中的子类设置的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133515/