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

Say I have the following headers:

@interface SuperClass  : NSObject

@interface SubClass : SuperClass

I highlight the class instance 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 a SuperClass, not a SubClass? Since SubClass is alloc'd / init'd, is this not possible?

Thank!

+3
source share
2 answers

If you always want the same line to come out, why not just:

NSString *classString = @"SuperClass";
0
source

If you always want to get a superclass,

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

alloc + init SubClass, cString "SuperClass", alloc + init SuperClass, cString "NSObject".

+5

Source: https://habr.com/ru/post/1749121/


All Articles