f. e. (只是为了更清楚地理解消息机制)我有课
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
调用[super allocWithZone:nil]
时,objc_msgSend实际上会发送什么?
objc_msgSend([MyClass class], "allocWithZone", nil)
或 objc_msgSend([NSObject class], "allocWithZone", nil)
?
实际上,我认为称为 objc_msgSend(self, "allocWithZone", nil)
,在这种情况下 self == [MyClass class];
我想确保为 ivar1 和 ivar2 分配内存。
当我们在类方法中调用 super 时,在 objc_msgSend() 函数中传递“self”参数,在我们的例子中是子类的类对象,这是真的吗? allocWithZone 会“查看”子类对象,看看应该为 ivar1 和 ivar2 分配多少内存。
谢谢!
最佳答案
任何发送给 super
的消息都会由编译器转换为 objc_msgSendSuper
(而不是 objc_msgSend
)。第一个参数是指向结构的指针。该结构包含一个指向当前实现的父类(super class)的指针和一个指向接收者的指针。前者在运行时需要搜索覆盖的实现,后者用作第一个参数。
对于类方法,接收者又是一个类指针,但与super_class
不同。在您的情况下,接收器是 MyClass
指针,而 super_class
指针将是 NSObject
。
两个旁注:我建议不要把精力花在编写最奇特的单例上。最好让开发人员自行创建实例或使用提供的共享实例。请注意double-checked locking is broken .
关于iphone - 调用[[super allocWithZone :nil] init],消息机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18249569/