简体   繁体   English

Objective-C获取子类

[英]Objective-C get subclass

Let's say I have a UIViewController Subclass, let's call it MyAppBaseViewController: and 假设我有一个UIViewController子类,我们将其称为MyAppBaseViewController:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSString *subclassName = ...;
    NSLog(@"%@ did appear", subclassName);
}

How would I be able to get the subclass name, not the name of the current class, from within the parent, without adding any properties to the implementation or anything like that? 我如何在不向实现中添加任何属性或类似内容的情况下从父级获取子类名称,而不是当前类的名称?

You are confused. 你很困惑。

An object is an instance of some subclass. 对象是某些子类的实例。 It can, and often does, inherit from a long chain of parent classes. 它可以并且经常从一长串父类继承。

The object is still a particular class. 该对象仍然是特定的类。

If you use 如果您使用

NSString *myClassName = [NSString stringWithFormat: @"%s", class_getName([self class)];

It will give you the name of the current object's class. 它将为您提供当前对象的类的名称。 Not the parent class. 不是父类。 The current object. 当前对象。

Edit: 编辑:

As the other poster pointed out, the function NSStringFromClass is much easier. 正如其他海报指出的那样,函数NSStringFromClass更加容易。 Use that instead: 改用它:

NSString *myClassName = NSStringFromClass([self class]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM