Skip to content

Instantly share code, notes, and snippets.

@mattjgalloway
Created August 20, 2013 09:36
Show Gist options
  • Save mattjgalloway/6279363 to your computer and use it in GitHub Desktop.
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
#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