public
Last active

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

  • Download Gist
MethodInProtocolsRequiredExample.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.