Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OBJ-C - Getting a class name from a class hierarchy

Let's say I have the following headers:

@interface SuperClass  : NSObject

@interface SubClass : SuperClass

I'm alloc'ing an instance of the class by doing:

 SubClass *sc = [[SubClass alloc] init];

In my SuperClass.m:

- (id) init
{
 self = [super init];
 if (self != nil)
 {
   NSString *cString = NSStringFromClass([self class]);
 }
 return self;
}

Simple, right? My question is: how can I get cString to return the SuperClass class, rather than the SubClass class? Since the SubClass is alloc'd/init'd, is this not possible?

Thanks!

like image 396
mmilo Avatar asked Dec 04 '25 19:12

mmilo


1 Answers

If you always want to get the super class,

- (id) init
{
    self = [super init];
    if (self)
    {
        NSString *cString = NSStringFromClass([self superclass]);
    }
    return self;
}

If you alloc+init a SubClass, then cString will contain “SuperClass”, but, if you alloc+init a SuperClass, then cString will contain “NSObject”.

like image 87
dreamlax Avatar answered Dec 06 '25 11:12

dreamlax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!