Objective-C:调用子类的类方法
假设我有一个名为 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 中完成这个任务吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您从另一个类方法向一个类方法发送消息时,self 就是该类。因此,您可以执行以下操作:
When you send a message to a class method from another class method, self is the class. Therefore, you can do the following:
您可以在类(静态)方法中使用 self 。在本例中,
self
指的是类对象。You can use
self
inside of a class (static) method. In this case,self
refers to the class object.