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

发布于 2024-11-26 16:04:04 字数 819 浏览 4 评论 0原文

假设我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光病人 2024-12-03 16:04:04

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

UIImage *img = [self backgroundImage];

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];
八巷 2024-12-03 16:04:04

您可以在类(静态)方法中使用 self 。在本例中,self 指的是类对象。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文