Is there any introspection method to get all accepted protocols for a class in Objective-C?

There is a method -[NSObject conformsToProtocol:] to check whether a particular protocol is accepted or not. Is there a way to get all accepted protocols for a class and not check the list?

+6
source share
3 answers

There is a more elegant solution: class_copyProtocolList() directly returns the accepted class protocols. Using:

 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); 
+11
source

There is exactly NSObject +conformsToProtocol ; protocol negotiation is declared as part of @interface , so it is not specific to each instance. For example,

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

No need to abandon C-level execution methods at least for the first question of your question. There is nothing in NSObject for a list of supported protocols.

+3
source

You can try objc_copyProtocolList

those. you get a list of all protocols, and then check if the current object matches a specific protocol by iterating the list.

Edit:

H2CO3 solution is really better

+1
source

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


All Articles