I am new in Objective-C and I am trying to create a singleton class based on Apple\'s documentation.
+ (MyGizmoClass*)sharedManager
{
if (sharedGizmoManager
(1.) What is super
in a 'static function'? In Objective-C, +methods are properly called class methods, -methods are called instance methods. These +methods are not true static methods because Objective-C classes are themselves objects of an opaque type called Class. So both super
and self
are defined in +methods. super
sends messages to the superclass of MyGizmoClass, but when called from a +method super
looks for an equivalent +method, and when called from an -method super
looks for a corresponding -method.self
in +methods of MyGizmoClass returns MyGizmoClass which is a Class, whereas in -methods self
is a pointer to a MyGizmoClass instance.
(2.) The method +class
returns self.isa
. Yes [super class]
invokes the superclass's:+class
method, however, when self
is passed up to +methods neither its value nor its type are modified (whereas self
's type is cast to the superclass when it is passed up through -methods). So when an implementation of the +class
method up the chain asks for self.isa
, it gets the same value, MyGizmoClass.
To be certain, you can verify that super
does call +class
in superclasses by deriving MyGizmoClass from a MyGizmoSuperClass where you can place an override:
@interface MyGizmoSuperClass : NSObject
@end
@implementation MyGizmoSuperClass
+(Class) class {
NSLog(@"yes it calls MyGizmoSuperClass:class");
return [super class];
}
@end
@interface MyGizmoClass : MyGizmoSuperClass
+(Class) classviasuper;
@end
@implementation MyGizmoClass
+(Class) classviasuper {
return [super class]; //which version of class will super call?
}
@end
int main(int argc, char *argv[])
{
NSLog(@"returned %@",[MyGizmoClass classviasuper]);
}
prints
yes it calls MyGizmoSuperClass:class
returned MyGizmoClass
(3.) Again super
calls the superclass version of allocWithZone
but the self
value passed to the method still points to a MyGizmoClass, and since allocWithZone
returns an object of the receiver's class, you get a MyGizmoClass back.
(4.) You can easily verify super
is different to self
. If you implement [self allocWithZone:NULL]
your code will call MyGizmoClass's implementation of allocWithZone
and loop indefinitely. With [super allocWithZone:NULL]
, the superclass's version gets called.