objective-cconvenience-methods

subclassing convenience construtctor


If I have a super class with a convenience constructor as follows (using ARC):

+(id)classA {
    ClassA *foo = [[ClassA alloc] init];

    return foo;
}

If I then subclass ClassA, with a class named ClassB, and I want to override the convenience constructor, is the following correct:

+(id)classB {
    ClassB *foo = [ClassA classA];

    return foo;
}


(Assume that I cannot call alloc and init on ClassB).

Thanks!


Solution

  • No, that is not correct, since that allocates, inits and returns a ClassA, not a ClassB. The only way to do this is not to use ClassA explicitly:

    + (id) classA
    {
        return [[self alloc] init];
    }
    

    Of course, you could also use old-fashioned new for this:

    ClassB *myB = [ClassB new];
    

    FWIW, assuming I would want to do more than just allocate and init, and my class is named Gadget, then I would do something like:

    + (id) gadgetWithNumber: (int) num
    {
        return [[self alloc] initWithNumber: num];
        // or without ARC:
        // return [[[self alloc] initWithNumber: num] autorelease];
    }
    

    Of course that assumes that there is an initWithNumber: method in my class.