Sending alloc: to super instead of allocWithZone:


#1

For BNRItemStore, the book suggested implementing sharedStore and allocWithZone: as follows:

+ (BNRItemStore *)sharedStore
{
    static BNRItemStore *sharedStore = nil;
    if (!sharedStore)
        sharedStore = [[super allocWithZone:nil] init];
    return sharedStore;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [self sharedStore];
}

That seems to work just fine. But there is something I don’t quite understand. It alloc does nothing more than invoke allocWithZone:, it would seem that I could replace super allocWithZone: with super alloc as follows:

        sharedStore = [[super alloc] init];

However, if I do that it results in an infinite loop where super alloc ends up sending allocWithZone: to self. Why is that? Why would super’s alloc ever invoke self’s allocWithZone:?


#2

That’s because [super alloc] is doing a [self allocWithZone:nil].

However, inside the super (class) object self refers to the BNRItemStore (class) object. Hence the recursion.


#3

wow, that’s crazy.

so if i have this right, in the line:

sharedStore = [[super allocWithZone:nil] init];

is calling:
(1) super’s allocWithZone:nil
(2) BNRItemStore’s init?


#4

The shareStore pointer is set to nil every time the method is called. How is this not abandoning the object pointed to if it already existed?


#5

I think I get it. A static pointer can only be set once and stays set, pointing to the same object, throughout the life of the program. The attempted resetting of the pointer with repeated calls of the method does nothing because of the nature of a static pointer.