Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Go direct to the Objective-C runtime:</p> <pre><code>#import &lt;objc/runtime.h&gt; /* 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-&gt;isa, [NSObject class]) ... </code></pre> <p><code>class_getSuperclass</code> does what it says, and it's safe to compare metaclasses by pointer in the Objective-C runtime because there is only exactly one instance of the metaclass for each class. The isa pointer is the only thing that's definitely in struct objc_object.</p> <p>EDIT: additionally, there are known bugs in the iPhone simulator that cause some exceptions not to be caught by try/catch blocks. I've reported them as a bug to Apple and been told that mine was a duplicate, so they are definitely aware. Did you try your code on a real device or just in the simulator?</p> <p>EDIT2: from the wider context given elsewhere in this conversation, something like this might be smarter:</p> <pre><code>#import &lt;objc/runtime.h&gt; BOOL classRespondsToSelector(Class classA, SEL selector) { return class_getInstanceMethod(classA, selector) ? YES : NO; } .... if(classRespondsToSelector(instance-&gt;isa, @selector(respondsToSelector:)) { // great, we've got something that responds to respondsToSelector:; do the // rest of our querying through there } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload