How to check if a class implements all methods in a protocol in Obj-C?

If an object conforms to a specific protocol in Objective-C, is there a way to check if it matches all the methods in that protocol. I would prefer to avoid explicitly checking every available method.

thanks

+4
source share
1 answer

You can get all the methods declared in the protocol using protocol_copyMethodDescriptionListthat returns a pointer to objc_method_descriptionstructs.

objc_method_descriptiondefined in objc/runtime.h:

struct objc_method_description {
    SEL name;               /**< The name of the method */
    char *types;            /**< The types of the method arguments */
};

To find out if class instances respond to a selector instancesRespondToSelector:

Leaving you with this function:

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;
}
+5
source

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


All Articles