简体   繁体   中英

Calling [[super allocWithZone:nil] init], messaging mechanism

fe (just for understanding messages mechanism more clear) I have class

MyClass.h

@interface MyClass : NSObject {
   int ivar1;
   int ivar2;
}

+ (id)instance;

@end

MyClass.m

static MyClass* volatile _sInstance = nil;

@implementation MyClass

+ (id)instance {
       if (!_sInstance) {
       @synchronized(self) {
           if (!_sInstance) {
               _sInstance = [[super allocWithZone:nil] init];
           }
       }
   }
   return _sInstance;
}

@end

What will be send in objc_msgSend in fact when calling [super allocWithZone:nil] ?

objc_msgSend([MyClass class], "allocWithZone", nil) or objc_msgSend([NSObject class], "allocWithZone", nil) ?

In practice I think that called objc_msgSend(self, "allocWithZone", nil) and in that case self == [MyClass class];

I want to be sure that memory for ivar1 and ivar2 will be allocated.

Is it true, that when we call super in class method, in objc_msgSend() function the "self" argument is passed, that in our case is class object of child? And allocWithZone will "look" at the child class object to see how much memory should be allocated for ivar1 and ivar2.

Thanks!

Any message to super is translated by the compiler to objc_msgSendSuper (not objc_msgSend ). The first argument is a pointer to a struct. The struct contains a pointer to the super class of the current implementation and the a pointer to the receiver. The former is needed during runtime to search for the overridden implementation, the latter is used as the first argument.

In the case of a class method the receiver is again a class pointer, yet not the same as the super_class . In your case the receiver is a MyClass pointer while the super_class pointer would be NSObject .

Two side notes: I recommend against putting energy in writing the fanciest Singleton. Better leave it up to the developer to create his own instances or use the provided shared instance. And please note that double-checked locking is broken .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM