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

objective-c, protocols

Solution

You can get all methods declared in a protocol with `protocol_copyMethodDescriptionList`, which returns a pointer to `objc_method_description` structs.

`objc_method_description` is defined 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 instances of a class respond to a selector use `instancesRespondToSelector:`

Leaving you with a function like this:

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;
}

Problem

If an object conforms to a certain protocol in Objective-C, is there a way to check if it conforms all the methods in that protocol. I would rather avoid explicitly checking each available method. Thanks

Original source

Related problems