如何检查类是否实现了Obj-C协议中的所有方法?

cgo*_*ain 4 protocols objective-c

如果一个对象符合Objective-C中的某个协议,是否有办法检查它是否符合该协议中的所有方法.我宁愿避免明确检查每个可用的方法.

谢谢

Seb*_*ian 5

您可以获取协议中声明的所有方法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 */
};
Run Code Online (Sandbox Code Playgroud)

要确定类的实例是否响应选择器使用 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;
}
Run Code Online (Sandbox Code Playgroud)