How to determine if a class inherits from NSObject (Objective-C)

I work in Objective-C on the iPhone and need to know if the "class" inherits from "NSObject".

I tried to check if it responds to the NSObject selector:

bool success = [myClass respondsToSelector:@selector(class)];

but you can guess what happened ... he didn't even answer "responsesToSelector:", so he throws an exception "does not implement doesNotRecognizeSelector:".

I tried to catch this exception, but it looks like it cannot be caught using @ try- @ catch.

Any ideas?

+3
source share
4 answers

Go straight to the Objective-C runtime:

#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.

EDIT: , 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
}
+7

isKindOfClass: isMemberOfClass:, , .

+4

respondsToSelector: , NSObject, . , , Objective-C.

, , NSObject? Apple .

+1

'Class' NSObject. , , NSObject (, isKindOfClass respondsToSelector), .

?

-3

Source: https://habr.com/ru/post/1776343/


All Articles