Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

super allocWithZone having some doubts in singleton class concept

Tags:

objective-c

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];
}

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.

I have some questions:

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

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

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

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

like image 422
sachin Avatar asked Aug 06 '12 10:08

sachin


1 Answers

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. I answered this question with reference to self, here is the paraphrased, important part of the answer

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

  2. This one was throwing me off too. I asked this question and it was concluded:

    [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].

  3. Are you sure it's actually returning an instance of this class? Or are you assigning it to an instance sharedGizmoManager of this class?

  4. 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.

like image 182
James Webster Avatar answered Oct 27 '22 01:10

James Webster