Objective-C运行时:检查类是否符合协议的最佳方式?

时间:2022-09-02 10:10:02

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.

我有一个类(但没有实例),需要知道它是否符合某个协议。但是,类可以被子类化多次,class_conformsToProtocol()会忽略在超类上声明的协议。

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?

我可以使用class_getSuperclass()递归地向上检查层次结构中的所有类,直到超类为nil。但是,我想知道,对于嵌套很深的类层次结构来说,这是否效率低下,也许有更好的方法来实现这一点?

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

换句话说,NSObject方法conformsToProtocol如何最好地利用Objective-C运行时方法来实现,以便在超类上找到协议?

 [myObject conformsToProtocol:@protocol(MyProtocol)];

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

如果我正处在递归向上的类层次结构的正确轨道上请让我知道。

2 个解决方案

#1


290  

According to the docs,

根据文档,

[MyClass conformsToProtocol:@protocol(MyProtocol)];

should work.

应该工作。

#2


1  

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

或者,如果是一个通用指针,比如:

Class<MyProtocol> someClassPointer = nil;

you can use:

您可以使用:

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

#1


290  

According to the docs,

根据文档,

[MyClass conformsToProtocol:@protocol(MyProtocol)];

should work.

应该工作。

#2


1  

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

或者,如果是一个通用指针,比如:

Class<MyProtocol> someClassPointer = nil;

you can use:

您可以使用:

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