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:
If sharedManager
is static, how can it to access super
?
When I print [super class]
why does it give the current class name?
Why does [[super allocWithZone:NULL] init]
is return the current class object?
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.
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
This one was throwing me off too. I asked this question and it was concluded:
[super class]
calls thesuper
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]
.
Are you sure it's actually returning an instance of this class? Or are you assigning it to an instance sharedGizmoManager
of this 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With