首先需要引入#import <objc/runtime.h>
- (BOOL)realRespondsToSelector:(SEL)selector
{
BOOL result = NO;
u_int count;
Method *methods= class_copyMethodList([self class], &count);
for (int i = 0; i < count ; i++)
{
SEL name = method_getName(methods[i]);
if (name == selector)
{
result = YES;
break;
}
}
if (methods != NULL)
{
free(methods);
methods = NULL;
}
return result;
}
直接使用NSObject的respondsToSelector:是不能判斷一個(gè)方法到底是自己實(shí)現(xiàn)的還是其父類(lèi)實(shí)現(xiàn)的。
這里用到了runtime中的class_copyMethodList,該方法獲取到的方法列表不包括其父類(lèi)的。
打印出對(duì)象所有的方法:
u_int count;
Method *methods= class_copyMethodList([self class], &count);
for (int i = 0; i < count ; i++)
{
SEL name = method_getName(methods[i]);
NSString *strName = [NSString stringWithCString:sel_getName(name) encoding:NSUTF8StringEncoding];
NSLog(@"%@: %@", [self class], strName);
}