Last active
December 10, 2015 04:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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