Objective-C:子类的调用类方法

时间:2011-07-27 18:23:18

标签: objective-c subclass superclass class-method

假设我有一个名为MyBaseClass的Objective-C类和一个名为MySubclassedClass的子类。

MyBaseClass有两个类方法:

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

backgroundColor方法调用backgroundImage。如果它被限制在MyBaseClass中,我的backgroundColor方法看起来像

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

但我希望能够将MyBaseClass子类化为MySubclassedClass。 backgroundColor不会更改并始终调用父级的backgroundImage方法。在这种情况下,backgroundImage将在每个子类中被覆盖。

如果1backgroundColor1是实例方法,我只需使用

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

但是,当它是静态方法时,我没有“自我”。

我可以在Objective-C中实现这一目标吗?

2 个答案:

答案 0 :(得分:12)

当您从另一个类方法向类方法发送消息时,self就是该类。因此,您可以执行以下操作:

UIImage *img = [self backgroundImage];

答案 1 :(得分:4)

您可以在类(静态)方法中使用self。在这种情况下,self引用类对象。

相关问题