Skip to content

Instantly share code, notes, and snippets.

@alexrozanski
Last active February 22, 2017 10:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexrozanski/7400817 to your computer and use it in GitHub Desktop.
Save alexrozanski/7400817 to your computer and use it in GitHub Desktop.
Gets information about all methods that are defined in an Objective-C protocol. Returns an array of dictionaries with the selector and argument types for each method in NSString form.
#import <Foundation/Foundation.h>
extern NSString * const PXProtocolMethodListMethodNameKey;
extern NSString * const PXProtocolMethodListArgumentTypesKey;
NSArray *px_allProtocolMethods(Protocol *protocol);
#import <objc/runtime.h>
NSString * const PXProtocolMethodListMethodNameKey = @"methodName";
NSString * const PXProtocolMethodListArgumentTypesKey = @"types";
NSArray *px_allProtocolMethods(Protocol *protocol)
{
NSMutableArray *methodList = [[NSMutableArray alloc] init];
// We have 4 permutations as protocol_copyMethodDescriptionList() takes two BOOL arguments for the types of methods to return.
for (NSUInteger i = 0; i < 4; ++i) {
unsigned int numberOfMethodDescriptions = 0;
struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, (i / 2) % 2, i % 2, &numberOfMethodDescriptions);
for (unsigned int j = 0; j < numberOfMethodDescriptions; ++j) {
struct objc_method_description methodDescription = methodDescriptions[j];
[methodList addObject:@{PXProtocolMethodListMethodNameKey: NSStringFromSelector(methodDescription.name),
PXProtocolMethodListArgumentTypesKey: [NSString stringWithUTF8String:methodDescription.types]}];
}
free(methodDescriptions);
}
return methodList;
}
@brandFromNSK
Copy link

Thanks ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment