开发者

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 ch开发者_C百科eck 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?


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

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


I can only assume your class hierarchy is wrong. Using the exact same code above, I'm getting YES as you would expect. Have you tried doing the following:

NSLog(@"%@ %@", NSClassFromString(@"MyInheritedObject"), [MyInheritedObject class]);

See if the outputs match up. The code you have posted is fine, so it has to be an issue with either MyInheritedObject or MyBaseObject. I'd double check your class hierarchy and also make sure you're using prefixes on your class names, just on the off chance theirs a naming collision (though the runtime should warn you of that in the console)


I have a similar problem where the test on type (obtained from NSClassFromString):

[type isSubclassOfClass:[AKABindingProvider class]]

fails, and this test

[type isSubclassOfClass:NSClassFromString(NSStringFromClass([AKABindingProvider class]))]

succeeds.

In my case this happens only inside Xcode, when the code is run in the course of "Editor->Refresh all views" in Interface Builder. When run in the app there seems to be no problem. My code is part of an iOS8 framework (and as such dynamically linked).

I guess that for whatever strange reason, classes gotten from [X class] and those obtained with NSClassFromString do not belong to the same inheritance hierarchy.

Can you verify that when both classes are obtained from NSClassFromString, your test would work?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜