Search code examples
objective-csubclasssuperclassclass-method

Objective-C: Call Class Method of Subclass


Let's say I have an Objective-C class called MyBaseClass and a subclass called MySubclassedClass.

The MyBaseClass has two class methods:

+ (UIColor *)backgroundColor;
+ (UIImage *)backgroundImage;

The backgroundColor method calls backgroundImage. If it was confined to MyBaseClass, my backgroundColor method would look like

+ (UIColor *)backgroundColor {
     UIImage *img = [MyBaseClass backgroundImage];
     // irrelevant
     return color;
}

But I want to be able to subclass MyBaseClass to MySubclassedClass. backgroundColor would not change and always call the parent's backgroundImage method. In this scenario, backgroundImage would be overridden in every subclass.

If 1backgroundColor1 was an instance method, I would simply use

UIImage *img = [[self class] backgroundImage];

but, there is no 'self' I can use when it's a static method.

Is there some away I can accomplish this in Objective-C?


Solution

  • When you send a message to a class method from another class method, self is the class. Therefore, you can do the following:

    UIImage *img = [self backgroundImage];