2

If I have access to an objective-C Protocol and trying to figure out how to look inside it to see what methods it contains, including their signatures, etc.

I've tried NSLog and looking in the object in the debugger, as well as on the internet, and cannot find any way to do this.

Locksleyu
  • 5,192
  • 8
  • 52
  • 77
  • Look at the .h file that defines the protocol? What do you mean "have access to?" – Paulw11 Nov 17 '15 at 21:27
  • 1
    A protocol does not "contain" any methods. It merely defines requirements for methods that must be implemented by whoever adopts (conforms to) the protocol. – matt Nov 17 '15 at 21:30

1 Answers1

4

I checked out the methods in objc/runtime.h after seeing the answers to this SO post: List selectors for Objective-C object and found a way to NSLog a protocol's method signatures

#import <objc/runtime.h>

Protocol *protocol = @protocol(UITableViewDelegate);

BOOL showRequiredMethods = NO;
BOOL showInstanceMethods = YES;

unsigned int methodCount = 0;
struct objc_method_description *methods = protocol_copyMethodDescriptionList(protocol, showrequiredMethods, showInstanceMethods, &methodCount);

NSLog(@"%d required instance methods found:", methodCount);

for (int i = 0; i < methodCount; i++)
{
    struct objc_method_description methodDescription = methods[i];
    NSLog(@"Method #%d: %@", i, NSStringFromSelector(methodDescription.name));
}

free(methods)

The only catch is that in protocol_copyMethodDescriptionList you need to specify whether you want required vs. non-required methods and whether you want class vs. instance methods. So to cover all four cases, you would need to call protocol_copyMethodDescriptionList four times and print the results for each list.

Community
  • 1
  • 1
Rob T
  • 147
  • 1
  • 6
  • @dreamlax correct, thanks - in a normal app you would definitely want to consider manual memory management – Rob T Nov 17 '15 at 23:13