Super linked statically at compile time?

I want to create a class cluster with a base class and two subclasses. Creating an instance of a base class should return a subclass based on some conditions, but creating a subclass directly must create it. I wrote the following code in a 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 alloc
    return [super allocWithZone:zone];
}

and it works, but I'm really surprised that it is. Namely, when called in a subclass, why is the superclass of the Base class (NSObject) superclassed rather than the base class (because it is called on SubclassA, the superclass is the base class)? It is as if a call to allocWithZone: a method inherited from Base is always always evaluated super relative to the base, rather than the actual execution class of the caller. I think that similar code in Java and other OO languages ​​will not work and lead to infinite recursion, right? Is this code wrong?

+3
source share
1 answer

. [super ...] , . +allocWithZone: Base, [super allocWithZone:zone] Base +allocWithZone: .

+2

All Articles