Neil
Neil

Reputation: 1853

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?

Upvotes: 4

Views: 1950

Answers (2)

user858224
user858224

Reputation:

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];

Upvotes: 12

highlycaffeinated
highlycaffeinated

Reputation: 19867

You can use self inside of a class (static) method. In this case, self refers to the class object.

Upvotes: 4

Related Questions