Search code examples
objective-cintrospectionobjective-c-runtimeobjective-c-protocol

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


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?


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