unom
unom

Reputation: 11486

Correct way to find out all the superclasses of a Class in Objective-C?

I'm a novice, and I seem to be getting multiple errors on this. All I want is a for or while loop to print out all the superclasses of a certain Class.

Here is the pseudocode of what I want:

IDontKnowWhatClass *superClassName;

while (superClassName != nil)
{
    superClassName = [[superClassName class] superclass];
    NSLog(print the name);
}

Upvotes: 0

Views: 112

Answers (4)

kkarayannis
kkarayannis

Reputation: 198

NSString* classString = @"IDontKnowWhatClass";
Class class = NSClassFromString(classString);
while (class != nil){
    NSLog(@"%@", [class description]);
    class = [class superclass];
}

Upvotes: 1

Johnykutty
Johnykutty

Reputation: 12859

Try this

Class superClassName = [self class];

while (superClassName != nil)
{
        superClassName = [superClassName superclass];
        NSLog(@"%@",NSStringFromClass(superClassName));
}

If you know a class itself like NSString then,

Class superClassName = [NSString class];

You can store the class name to a string like

NSString *className = NSStringFromClass(superClassName);

And if you want to create an object of the class from which class name is stored in a string like

id object = [[NSClassFromString(className) alloc] init];

Upvotes: 1

Vladimir
Vladimir

Reputation: 170849

You can call superclass method on your current class until it gets equal to Nil (that will happen for root class, i.e. NSObject).

Class c = [IDontKnowWhatClass class];

while (c)
{
    NSLog(@"%@", NSStringFromClass(c));
    c = [c superclass];
}

Upvotes: 1

Samkit Jain
Samkit Jain

Reputation: 2533

Use NSObject method names as :

objc_property_t class_getProperty(Class cls, const char *name)

//Returns a property with a given name of a given class.

Keep on finding till you get the NSObject as it is supermost class

Use this method to check for equality :

- (BOOL)isEqual:(id)object;

or

[object isKindOfClass:[SomeClass class]]

Documentation here

This will work

Upvotes: 1

Related Questions