假设我有一个名为 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];
但是,当它是静态方法时,我无法使用“self”。
在 Objective-C 中我还有什么办法可以完成这个吗?
最佳答案
当您从另一个类方法向一个类方法发送消息时,self 就是该类。因此,您可以执行以下操作:
UIImage *img = [self backgroundImage];
关于Objective-C:调用子类的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6849268/