views:

148

answers:

1

Hi, 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. f.e.

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

Now f.e. 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. So im asking if theres a better approach to accomplish this? either with the ability to modify the superclass or without.

thanks a lot

A: 

Generally, you have one init* method variant that is the designated initializer. All other init* methods call through to that one and then do whatever customization they need. 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).

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.)

bbum