Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSClassFromString returns a Class object which doesn't respond to isSubClassOfClass properly

I have a class that I'm testing which uses a lot of run-time type identification (reflection) to make decisions about how to behave.

Specifically, I get the Class of a given type using property_getAttributes and a little string magic.

Say the parsed class is MyInheritedObject. I then need to check if this class inherits from a common base class MyBaseObject.

So, given the string: "MyInheritedObject", I use NSClassFromString to get a class instance, like this:

NSString *className = @"MyInheritedObject";
Class cls = NSClassFromString(className);
BOOL isSubclass = [cls isSubclassOfClass:[MyBaseObject class]];

This returns NO, which is incredibly puzzling. If I log out the super class though, it looks like it should be working:

NSLog(@"Superclass: %@", [cls superclass]);
//logs:  Superclass: MyInheritedObject

So for the time-being I'm using the string comparison to continue on with my work, but it's a terrible hackety-hack and I can't leave it this way.

Not sure if it's related, but this is happening from a test target, so the classes in question are added to both targets.

Any ideas on what's going on here?

like image 743
Ben Scheirman Avatar asked Dec 22 '25 05:12

Ben Scheirman


1 Answers

NSString *className = @"MyInheritedObject";
Class indirectClass = NSClassFromString(className);
Class directClass = [MyInheritedObject class];
BOOL isSubclass = [indirectClass isSubclassOfClass:directClass];

If you do this, does (indirectClass == directClass) ?

like image 64
bshirley Avatar answered Dec 23 '25 20:12

bshirley



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!