直接进入 Objective-C 运行时:
#import <objc/runtime.h>
/* originally posted version — works because eventually class_getSuperclass(class)
returns nil, and class_getSuperclass(nil) does so also. */
BOOL classDescendsFromClass(Class classA, Class classB)
{
while(1)
{
if(classA == classB) return YES;
id superClass = class_getSuperclass(classA);
if(classA == superClass) return (superClass == classB);
classA = superClass;
}
}
/* shorter version; exits straight after classA turns into nil */
BOOL classDescendsFromClassShorter(Class classA, Class classB)
{
while(classA)
{
if(classA == classB) return YES;
classA = class_getSuperclass(classA);
}
return NO;
}
...
if(classDescendsFromClass(classToTest->isa, [NSObject class]) ...
class_getSuperclass
做它所说的,并且在Objective-C运行时通过指针比较元类是安全的,因为每个类只有一个元类的实例。isa 指针是唯一肯定在 struct objc_object 中的东西。
编辑:此外,iPhone 模拟器中存在已知的错误,这些错误会导致某些异常不会被 try/catch 块捕获。我已将它们作为错误报告给 Apple,并被告知我的是重复的,所以他们肯定知道。您是在真实设备上还是仅在模拟器中尝试您的代码?
EDIT2:从本次对话其他地方给出的更广泛的背景来看,这样的事情可能更聪明:
#import <objc/runtime.h>
BOOL classRespondsToSelector(Class classA, SEL selector)
{
return class_getInstanceMethod(classA, selector) ? YES : NO;
}
....
if(classRespondsToSelector(instance->isa, @selector(respondsToSelector:))
{
// great, we've got something that responds to respondsToSelector:; do the
// rest of our querying through there
}