jglievano
jglievano

Reputation: 501

How to call a subclass' method from the parent class implementation?

In Objective-C, say you have class Parent:

@interface Parent : NSObject
@end

@implementation

+ (void)load {
  NSLog(@"class: %@", NSStringFromClass([self class]);
}

@end

and class Child:

@interface Child : Parent
@end

How can I make this so whenever +[Child load] gets called it logs the name of Child instead of the name of Parent? I'd prefer if I don't have to rewrite + (void)load on each subclass of Parent.

Upvotes: 0

Views: 87

Answers (1)

André Slotta
André Slotta

Reputation: 14030

load is an existing method (https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/#//apple_ref/occ/clm/NSObject/load).

lets say we have the following classes:

@interface Parent : NSObject
+ (void)logClassName;
@end

@implementation Parent
+ (void)logClassName {
  NSLog(@"class: %@", NSStringFromClass(self));
}
@end

@interface Child : Parent
@end

now when i call the logClassName class method...

[Parent logClassName];
[Child logClassName];

i get the following output which is - if i got you right - exactly what you wanted:

2015-11-11 22:56:19.029 OOP[676:11008] class: Parent
2015-11-11 22:56:19.030 OOP[676:11008] class: Child

Upvotes: 1

Related Questions