3
votes

I want to create a class cluster with a base class and 2 subclasses. Creating an instance of the base class should return a subclass based on some conditions, but creating a subclass directly should create it. I wrote the following code in the base class:

+ (id)allocWithZone:(NSZone *)zone {
    // prevent infinite recursion
    if ([self isEqual:Base.class]) {
        // if self is the base class, return a correct subclass
        if (somecondition) {
            return [SubclassA alloc];
        }
        return [SubclassB alloc];
    }
    // otherwise, alloc is called on a subclass
    // call NSObject's alloc
    return [super allocWithZone:zone];
}

and it works, but I'm really surprised that it does. Namely, when invoked on a subclass, why does super evaluate to the Base class's superclass (NSObject), and not the Base class (because invoked on SubclassA, the superclass is Base)? It is as if the allocWithZone: method call, inherited from Base, just always evaluated super relative to Base, not the real runtime class of the caller. I think similar code in Java and other OO languages would not work and result in infinite recursion, would it? Is this code wrong?

1

1 Answers

2
votes

Your code is correct. [super ...] always uses the superclass of the class implementing the method. In your code, +allocWithZone: is implemented by class Base, so [super allocWithZone:zone] uses Base's superclass when searching for the next +allocWithZone: implementation to call.