super allocWithZone 对单例类概念有一些疑问 [英] super allocWithZone having some doubts in singleton class concept

查看:51
本文介绍了super allocWithZone 对单例类概念有一些疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Objective-C 的新手,我正在尝试基于 Apple 的文档.

I am new in Objective-C and I am trying to create a singleton class based on Apple's documentation.

+ (MyGizmoClass*)sharedManager
{
    if (sharedGizmoManager == nil) {
        sharedGizmoManager = [[super allocWithZone:NULL] init];
    }
    return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedManager] retain];
}

在这段代码中,sharedManager 是一个静态方法,它会检查这个类的对象是否存在.如果是,它将返回之前创建的对象,否则创建一个新对象.

In this code sharedManager is a static method which will check if object of this class is present. If so it will return the previous created object, otherwise it create a new one.

我有一些问题:

  1. 如果sharedManager是静态的,它如何访问super?

  1. If sharedManager is static, how can it to access super?

当我打印[super class]时,为什么它给出了当前的类名?

When I print [super class] why does it give the current class name?

为什么[[super allocWithZone:NULL] init]是返回当前的类对象?

Why does [[super allocWithZone:NULL] init] is return the current class object?

如果 super 在这里等于 self 那么为什么它不调用当前类的 allocWithZone:(NSZone *)zone?

If super is equal to self here than why its not calling current class's allocWithZone:(NSZone *)zone?

推荐答案

其他答案虽然指出了关于单身人士的好信息,但实际上并没有回答您的问题.您的问题实际上主要是基于面向对象的,您专门引用单例的事实是偶然的.

The other answers, though they point out good information with regard to singletons, didn't actually answer your question. Your question is actually mostly based on Object orientation, the fact that you specifically reference a singleton is incidental.

  1. 我参考self回答了这个问题,这里是释义,答案的重要部分

  1. I answered this question with reference to self, here is the paraphrased, important part of the answer

super 在类级别上下文中确实有意义,但它指的是超类本身,而不是实例

super does have meaning in class level contexts, but it refers to the superclass itself, not an instance

  • 这个也让我失望了.我问了这个问题,得出的结论是:

    [super class] 在当前实例(即 self)上调用 super 方法.如果 self 有一个被覆盖的版本,那么它会被调用并且看起来会有所不同.既然你没有覆盖它,调用[self class]和调用[super class]是一样的.

    [super class] calls the super method on the current instance (i.e. self). If self had an overridden version, then it would be called and it would look different. Since you don't override it, calling [self class] is the same as calling [super class].

  • 你确定它真的返回了这个类的一个实例吗?或者您是否将其分配给此类的实例 sharedGizmoManager?

    Super 不等于 self,而是你调用的一些方法:例如[super class] 正在调用 [self class] 将调用的方法的相同实现.

    Super isn't equal to self, but some of the methods you have called: e.g. [super class] is calling the same implementation of the method that [self class] would call.

    这篇关于super allocWithZone 对单例类概念有一些疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆