Created
August 20, 2013 09:36
-
-
Save mattjgalloway/6279363 to your computer and use it in GitHub Desktop.
Check if something responds to a certain selector, searching up until a certain class
This file contains hidden or 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 <UIKit/UIKit.h> | |
#import <objc/runtime.h> | |
@interface NSObject (MJGResponds) | |
+ (BOOL)mjg_hasImplementationForSelector:(SEL)selector searchUntilClass:(Class)cls; | |
@end | |
@implementation NSObject (MJGResponds) | |
+ (BOOL)mjg_hasImplementationForSelector:(SEL)selector searchUntilClass:(Class)cls { | |
Class currentClass = self; | |
BOOL found = NO; | |
while (currentClass && currentClass != cls) { | |
int unsigned numberOfMethods; | |
Method *methods = class_copyMethodList(currentClass, &numberOfMethods); | |
for (int i = 0; i < numberOfMethods; i++) { | |
if (selector == method_getName(methods[i])) { | |
found = YES; | |
break; | |
} | |
} | |
currentClass = class_getSuperclass(currentClass); | |
} | |
if (found) return YES; | |
return NO; | |
} | |
@end | |
@interface MyView : UIView @end | |
@implementation MyView | |
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {} | |
@end | |
@interface MyView2 : MyView @end | |
@implementation MyView2 @end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
BOOL has = [MyView2 mjg_hasImplementationForSelector:@selector(touchesBegan:withEvent:) searchUntilClass:[UIView class]]; | |
NSLog(@"has = %i", has); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment