简体   繁体   中英

Objective-C get subclass

Let's say I have a UIViewController Subclass, let's call it MyAppBaseViewController: and

- (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. Use that instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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