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

发布于 2024-09-06 23:45:10 字数 406 浏览 2 评论 0原文

我有 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 技术交流群。

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

发布评论

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

评论(2

病女 2024-09-13 23:45:10

如果您只想将其记录/获取为类,则只需要 self。就是这样。同样

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

+ (void)func {
    NSLog(@"%@ call func", 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 like

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

or

+ (void)func {
    NSLog(@"%@ call func", 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)

赢得她心 2024-09-13 23:45:10

要获取当前类对象,您应该能够执行以下操作:

[self class];

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

编辑以避免混淆...

To get the current class object, you should be able to do:

[self class];

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...

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