How do I know if an instance implements a method in Objective-C?

I would like to know if an instance implements a specific method. I could use respondsToSelector: but it returns YES if the instance inherits the method ...

I could have skipped class_copyMethodList() methods, but since I could have tested many instances, I wanted to know if there was a simpler solution (e.g. repondsToSelector: but limited to the class itself) ..)

edit: since I really think that there is no function or method, I wrote this. Thanks for your answers, here is this method, if it can be useful:

 + (BOOL)class:(Class)aClass implementsSelector:(SEL)aSelector { Method *methods; unsigned int count; unsigned int i; methods = class_copyMethodList(aClass, &count); BOOL implementsSelector = NO; for (i = 0; i < count; i++) { if (sel_isEqual(method_getName(methods[i]), aSelector)) { implementsSelector = YES; break; } } free(methods); return implementsSelector; } 
+4
source share
3 answers

You can use reflection for this.

+1
source

It is probably easier to check if the method returned by your own class is the same or different from the method that your superclass returns.

 if ([[obj class] instanceMethodForSelector:sel] != [[obj superclass] instanceMethodForSelector:sel]) { NSLog(@"%@ directly implements %@", [obj class], NSStringFromSelector(sel)); } 
+3
source

The instance responds and does not super:

 -(BOOL) declaresSelector:(SEL)inSelector { return [self respondsToSelector:inSelector] && ![super respondsToSelector:inSelector]; } 

The instance responds and differs from super:

 -(BOOL) implementsSelector:(SEL)inSelector { return [self respondsToSelector:inSelector] && !( [super respondsToSelector:inSelector] && [self methodForSelector:inSelector] == [super methodForSelector:inSelector] ); } 

According to Apple docs, you should call responsesToSelector before methodForSelector.

+3
source

Source: https://habr.com/ru/post/1305978/


All Articles