I expected [super class]
to return the superclass's class, however I found, using this code that it returns this class's class.
Code
NSLogObject([self class]);
NSLogObject([super class]);
NSLogObject([self superclass]);
NSLogBool([self class] == [super class]);
Output
[self class]: MainMenuScene
[super class]: MainMenuScene
[self superclass]: CCScene
[self class] == [super class]:[YES]
Can somebody explain why this happens please?. I expect it to return the same value as [self superclass]
.
Macros: ------- #define NSLogBool(i) NSLog(@"%s:[%@]", #i, (i) ? @"YES" : @"NO") #define NSLogObject(o) NSLog(@"%s:[%@]", #o, o)
super
refers to the method implementation in the superclass. If you don't override the method in your class, the implementation in your class and its superclass is the same.Both
[super class]
and[self class]
call the same method, defined onNSObject
.[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]
.While the answers by mprivat and Sulthan are technically correct, the current case is a bit more complicated (and interesting):
Considering the implementation of the call to the method. It uses (of course) the object pointer. An object pointer is a pointer to a struct that has as its first element (
isa
) is a pointer to the objects class. Theclass
methods (that is, as mprivat and Sulthan has stated correctly, the very same in both cases) follows this pointer to determine the class, i.e., always the class of the calling object.As a result, if A is the superclass of B, both calls
[self class]
and[super class]
called by an instance of B, return the class of B (not of A, what one may expect because of a missing override!).