2

f. e. (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!

4

1 回答 1

3

super编译器将任何消息转换为objc_msgSendSuper(not objc_msgSend)。第一个参数是一个指向结构的指针。该结构包含一个指向当前实现的超类的指针和一个指向接收器的指针。在运行时需要前者来搜索覆盖的实现,后者用作第一个参数。

在类方法的情况下,接收者又是一个类指针,但与super_class. 在您的情况下,接收器是一个MyClass指针,而super_class指针是NSObject.

两个旁注:我建议不要把精力放在写最花哨的单身人士身上。最好让开发人员自己创建实例或使用提供的共享实例。请注意,双重检查锁定已损坏

于 2013-08-15T09:37:48.753 回答