Objective-c:如何在类方法中获取类实例
我有 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
}
有没有办法在类方法中获取类实例(或类名)?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想将其记录/获取为类,则只需要
self
。就是这样。同样。
,如果您想获取 NSString 形式的名称,NSStringFromClass(self) 也能满足您的需求 (作为 char *,class_getName(self) 就是您要寻找的)
If you just want to log it/get it as a Class, you just need
self
. Thats it. So likeor
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)
要获取当前类对象,您应该能够执行以下操作:
因为 self 将引用类实例,因为它是一个类方法。 Class 是 NSObject 中定义的方法,它返回对象的类。
编辑以避免混淆...
To get the current class object, you should be able to do:
As self will refer to the class instance, because it's a class method. Class is a method defined in NSObject, which returns the class for the object.
Edited to avoid confusion...