Objective-C Runtime: best way to check if class conforms to protocol?

Objective CRuntime

Objective C Problem Overview


I have a Class (but no instance) and need to know if it conforms to a certain protocol. However, Class can be subclassed several times and class_conformsToProtocol() ignores protocols declared on superclasses.

I could just use class_getSuperclass() and recursively check all the classes in the hierarchy upwards until the superclass is nil. However I wonder if that might be inefficient for deeply nested class hierarchies, and maybe there's a nicer way to do that?

In other words, how is the NSObject method conformsToProtocol best implemented using Objective-C runtime methods so that it finds protocols on superclasses?

 [myObject conformsToProtocol:@protocol(MyProtocol)];

If I'm on the right track with recursively going up the class hierarchy just let me know.

Objective C Solutions


Solution 1 - Objective C

According to the docs,

[MyClass conformsToProtocol:@protocol(MyProtocol)];

should work.

Solution 2 - Objective C

Or, in case it is a general pointer, like:

Class<MyProtocol> someClassPointer = nil;

you can use:

[someClassPointer.class conformsToProtocol:@protocol(MyProtocol)];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLearnCocos2DView Question on Stackoverflow
Solution 1 - Objective CWevahView Answer on Stackoverflow
Solution 2 - Objective CNikitaView Answer on Stackoverflow