One More Question about Singleton


I have read all topics addressing Singleton in this forum, and I can understand why we use super instead of self, why we override allocWithZone and so on. However, I still have one more question about the next code.

defaultStore = [[super allocWithZone:NULL] init];

In the above code, the receiver of “allocWithZone:NULL” is “super.” Therefore, it allocates memory blocks for the super class of PossessionStore class. Do I understand correctly?

If YES, “my concern” is that the amount of memory for the super class must be different from the amount of memory for PossessionStore class. I think that the required memory size of PossessionStore class must be larger than that of the super class, because an instance variable, named allPossessions, is added. I just worry that the memory allocation via the above code may allocate insufficient memory for PossessionStore class.

I know that the code is correct and “my concern” is invalid. However, I don’t know why “my concern” is invalid. Please explain why…



As I understand it:

Every method call in ObjC is invoked by a call to objc_msgSend which has a couple of hidden parameters:
The receiving object (self) and the selector for the method _cmd

You can see these in any method with
NSLog(@"_cmd = %@",NSStringFromSelector(_cmd));
NSLog(@“self = %@”,self);

In an instance method, self refers to the actual object but in a class method self refers to the class.

So the call to [super allocWithZone:] is invoked on the superclass (in this case, NSObject) but knows which class to allocate memory for (PossessionStore) from the hidden self parameter and therefore accommodates the additional ivars.



Thank you!!