Mitchell Currie
Mitchell Currie

Reputation: 2809

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?

Upvotes: 0

Views: 876

Answers (1)

Duncan C
Duncan C

Reputation: 131491

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]);

Upvotes: 3

Related Questions