Objective-C:如何在类方法中获取Class实例

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)