7

我有 2 个类,Parent 和 Child,Parent 有一个名为 func 的类方法。现在我想在 func 方法中获取 Class 实例来区分哪个类是调用者。

@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
}

有没有办法在类方法中获取类实例(或类名)?

4

2 回答 2

17

如果您只想将其记录/获取为一个类,您只需要self. 就是这样。所以喜欢

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

或者

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

另外,如果你想获得一个 NSString 的名字,NSStringFromClass(self) 已经涵盖了。(作为一个 char *,class_getName(self) 就是你要找的)

于 2010-06-26T18:34:35.997 回答
3

要获取当前的类对象,您应该能够:

[self class];

因为 self 将引用类实例,因为它是一个类方法。Class 是 NSObject 中定义的一个方法,它返回对象的类。

编辑以避免混淆...

于 2010-06-26T18:20:30.813 回答