Search code examples
objective-cobjectinheritancedesignated-initializer

Initializing instance object in designated initializer?


I have a Rectangle class which has properties width and height. It also has an instance property/object called origin (-(XYPoint *) origin ). Below is the code for my designated initializer in which I pass the XYPoint object as an argument. Is there a way (or is it okay) if I take the properties of the XYPoint class as arguments in this method and then initialize the XYPoint object as well as allocate memory for it inside the method? Otherwise I have to create an XYPoint object in my main program and pass it as an argument which is a lot more code to type.

-(id) initWithWidth:(int)w andHeight:(int)h andOrigin:(XYPoint *)o
{
    self = [super init];
    if (self) {
        [self setWidth: w andHeight: h];
        self.origin = o;
    }
    return self;
}

P.S.- I am new to programming and Objective C so pardon me if I have stated something technically wrong in my question. Thanks!


Solution

  • Personally--I try to avoid initializers that take parameters. I think it leads to writing lots more code and inflexibility. I use designated initializers for just 2 things:

    • initializing an object with properties that must not be changed after the object is initialized
    • initializing an object with properties that are absolutely needed to construct it and cannot be specified later

    In general, for Rectangle class, I'd make the use like this:

    Rectangle * r = [ [ Rectangle alloc ] init ] ;
    r.x = x ;
    r.y = y ;
    r.origin = o ;
    
    // use r
    

    and not use the designated initializer pattern at all except for the conditions outlined above. (For example, creating immutable Rectangle instances)

    Finally, there's probably no need to create a Rectangle class--just use CGRect/NSRect primitive structures.