如果一个对象符合Objective-C中的某个协议,是否有一种方法可以检查它是否符合该协议中的所有方法。我宁愿避免明确检查每个可用方法。谢谢。
使用 protocol_copyMethodDescriptionList
可以获取协议中声明的所有方法, 它返回一个指向 objc_method_description
结构体的指针。
objc_method_description
在 objc/runtime.h
中定义:
struct objc_method_description {
SEL name; /**< The name of the method */
char *types; /**< The types of the method arguments */
};
要查找类的实例是否响应一个选择器,请使用instancesRespondToSelector:
这将使您拥有以下函数:
BOOL ClassImplementsAllMethodsInProtocol(Class class, Protocol *protocol) {
unsigned int count;
struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, NO, YES, &count);
BOOL implementsAll = YES;
for (unsigned int i = 0; i<count; i++) {
if (![class instancesRespondToSelector:methodDescriptions[i].name]) {
implementsAll = NO;
break;
}
}
free(methodDescriptions);
return implementsAll;
}