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

标签 iphone ios objective-c c nsobject

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/

相关文章:

ios - 带有自定义 UITableViewCells 的表单

ios - 我的导航栏不会显得清晰。

objective-c - 安全范围书签在 Yosemite 10.10 上停止工作

iphone - 不使用drawrect方法获取UIView的Context

ios - 我的 Mac App 需要申请 Server Entitlement Key 吗?

objective-c - 访问 UITableViewCell 的 TouchBegan/Moved/Ended

ios - UNIX时间转换swift iOS

iphone - 后台任务是这个问题的解决方案吗?

iphone - 从设置包中检索切换开关值

iphone - 检查缩放级别是否改变