Question

There is an -[NSObject conformsToProtocol:] method to check whether a specific protocol is adopted or not. Is there any method to get all adopted protocols for a class, rather than checking a list?

Was it helpful?

Solution

There's a more elegant solution: class_copyProtocolList() directly returns the adopted protocols of a class. Usage:

Class cls = [self class]; // or [NSArray class], etc.
unsigned count;
Protocol **pl = class_copyProtocolList(cls, &count);

for (unsigned i = 0; i < count; i++) {
    NSLog(@"Class %@ implements protocol <%s>", cls, protocol_getName(pl[i]));
}

free(pl);

OTHER TIPS

There is exactly NSObject +conformsToProtocol; protocol conformance is declared as part of the @interface so it isn't specific to each instance. So e.g.

if( [[self class] conformsToProtocol:@protocol(UIScrollViewDelegate)])
    NSLog(@"I claim to conform to UIScrollViewDelegate");

No need to drop down to the C-level runtime methods at all, at least for the first limb of your question. There's nothing in NSObject for getting a list of supported protocols.

You can try objc_copyProtocolList

I.e. you get the list of all protocols and then check if current object conforms to specific protocol by iterating the list.

Edit:

H2CO3 solution is really better one

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top