Reputation: 5972
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
Upvotes: 4
Views: 1308
Reputation: 7720
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;
}
Upvotes: 5