gpt4 book ai didi

iphone - 调用[[super allocWithZone :nil] init], 消息机制

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:09:12 26 4
gpt4 key购买 nike

e. (只是为了更清楚地理解消息机制)我有课

我的类.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”参数,在我们的例子中是 child 的类对象?而 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com