Objective-C:如何在类方法中获取Class实例 [英] Objective-c: How can I get Class instance in class method

查看:116
本文介绍了Objective-C:如何在类方法中获取Class实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个类,父级"和子级",并且父级"有一个名为func的类方法. 现在,我想在func方法中获取Class实例,以区分哪个类是调用者.

I have 2 classes, Parent and Child, and Parent has a class method named func. Now I want to get Class instance in func method to distinguish which class is caller.

@interface Parent : NSObject
+ (void)func;
@end

@implementation Parent

+ (void)func {
    Class *class = howToGetClass();
    NSLog(@"%@ call func", class);
}

@end

@interface Child : Parent
@end

int main() {
    [Child func];    // call func from Child
}

有什么方法可以在类方法中获取类实例(或类名)吗?

Is there any way to get class instance (or class name) in class method?

推荐答案

如果只想登录/获取它作为Class,则只需self.而已.就像

If you just want to log it/get it as a Class, you just need self. Thats it. So like

+ (void)func {
    Class class = self;
    NSLog(@"%@ call func", class);
}

+ (void)func {
    NSLog(@"%@ call func", self);
}

此外,如果您想以NSString作为名称,则可以使用NSStringFromClass(s​​elf). (作为char *,class_getName(self)是您要寻找的东西)

also, if you want to get the name as an NSString, NSStringFromClass(self) has you covered. (As a char *, class_getName(self) is what you're looking for)

这篇关于Objective-C:如何在类方法中获取Class实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆