简体   繁体   English

目标C-子类化具有多个初始化方法

[英]Objective C - subclassing classes with multiple init-methods

im searching for a convenient way of adding new arguments to multiple init-methods. 我正在寻找一种向多个初始化方法添加新参数的便捷方法。 its a little bit hard to discribe but my problem is the following: 它有点难以描述,但是我的问题是:

I have a class witch implements various init-methods. 我有一堂课,女巫实现了各种初始化方法。 fe FE

@interface Circle {
    CGPoint   center;
    float   radius;
}
- (id)initWithCenter:...radius:...;
- (id)initWithRect:...;  
- (id)initWithPoly:...;

Now fe i want to create a crosshair-class as a subclass. 现在我想创建一个十字准线类作为子类。 So i want to add maybe some lines as instance variables. 所以我想添加一些行作为实例变量。 So the problem is, every crosshair-object has to be initialized with some specific values, but of course the methods to initialize the circle wouldnt change. 因此,问题在于,每个十字准线对象都必须使用一些特定的值进行初始化,但是,初始化圆的方法当然不会改变。 so i want every init-method from the superclass but add those specific arguments to each. 所以我想要超类的每个初始化方法,但要向每个对象添加这些特定的参数。

the direct way (in my unexperienced eyes) is to overwrite each method in witch i then call the according super-method and afterwards do my stuff. 直接的方法(在我没有经验的眼睛中)是覆盖巫婆中的每个方法,然后调用相应的超级方法,然后再做我的事情。 But this is very annoying if youve got 10 or more init methods and just want to add the same arguments to each. 但是,如果您有10个或更多init方法,并且只想向每个方法添加相同的参数,这将非常烦人。 So im asking if theres a better approach to accomplish this? 所以我问是否有更好的方法来实现这一目标? either with the ability to modify the superclass or without. 具有修改超类的能力或没有的能力。

thanks a lot 非常感谢

Generally, you have one init* method variant that is the designated initializer . 通常,您有一个init*方法变体,它是指定的初始值设定项 All other init* methods call through to that one and then do whatever customization they need. 所有其他init*方法都调用该方法,然后进行所需的任何自定义。 Subclassers would generally either add new init* variants that call [self init*] on the designated initializer as the first thing or subclassers would override the designated initializer (and and others as needed). 子类通常会在第一件事上添加新的init*变体,这些变[self init*]在指定的初始值设定项上调用[self init*]或者子类会覆盖指定的初始值设定项(以及其他需要的初始值)。

However , this can rapidly get completely out of hand. 但是 ,这可以很快完全失去控制。 For your Circle, it really seems like you just want: 对于你的圈子,它真的好像你只是想:

- (id)initWithCenter:...radius:...;

And would then create a series of convenience factory methods to handle other types: 然后创建一系列便利工厂方法来处理其他类型:

+ circleInRect:...;

(I suspect your code is a contrived example or else I'd also point out the oddity that is a "crosshair" class as a subclass of a "circle" class. For something like that, I'd probably start with a Shape class, and then add Circle and Crosshair as a subclass of Shape. Obviously, the Sketch example is highly relevant.) (我怀疑您的代码是人为的示例,否则我还会指出作为“圆形”类的子类的“十字准线”类的奇怪之处。对于类似的事情,我可能会从Shape类开始,然后将CircleCrosshair添加为Shape的子类。显然, Sketch示例非常相关。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM