Skip to content

Instantly share code, notes, and snippets.

@armadsen
Last active December 10, 2015 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armadsen/4381753 to your computer and use it in GitHub Desktop.
Save armadsen/4381753 to your computer and use it in GitHub Desktop.
Complete example/test program for quick and dirty function to determine if a method in an Objective-C protocol is required or optional. Example for my answer to this stackoverflow question: http://stackoverflow.com/questions/14043930/how-to-identify-a-protocol-method-is-optional-during-runtime/14044086#14044086
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@protocol TestProtocol <NSObject>
@required
- (void)methodA;
@optional
- (void)methodB;
@end
@interface TestProtocolClass : NSObject <TestProtocol> @end
@implementation TestProtocolClass
- (void)methodA
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
@end
BOOL MethodInProtocolIsRequired(Protocol *protocol, SEL methodSelector)
{
struct objc_method_description methodDesc = protocol_getMethodDescription(protocol, methodSelector, YES, YES);
return methodDesc.name != NULL;
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
Protocol *p = objc_getProtocol("TestProtocol");
BOOL methodAIsRequired = MethodInProtocolIsRequired(p, @selector(methodA));
BOOL methodBIsRequired = MethodInProtocolIsRequired(p, @selector(methodB));
NSLog(@"methodA is required? %i methodB is required? %i", methodAIsRequired, methodBIsRequired);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment