How to find out if a method exists in Obj-C when setting an NSString

I have a method NSString *. If it exists, I want to call it, and if not, do nothing.

SEL eventSelector = NSSelectorFromString(eventSelectorStr);
if ([delegate respondsToSelector:eventSelector]) {
    [delegate performSelector:eventSelector];
    [delegate adapterDidFinishAdRequest:self];
}
else {
    // Does not implement selector
}

This code does not work because it NSSelectorFromStringwill register the string as a selector, therefore it respondsToSelector:eventSelectorwill fail because the selector is actually invalid.

+3
source share
4 answers

Why are you saying this is not working? This is the most common way to implement additional delegation methods. I have never had a problem with this design not working.

+5
source

Let me clarify some confusion.

NSSelectorFromString() . respondsToSelector: , , . , performSelector: , , .

. . , adapterDidFinishAdRequest:.

+1

eventSelector != nil .

0

, . , C, - . NSSelectorFromString() , "", , C "" ( ) Objective-C.

NSSelectorFromString() Apple:

, aSelectorName. aSelectorName nil UTF-8 ( - ), (SEL)0.

After carefully reading this, it is shown that the only situations that can lead to a return (SEL)0are that your string was nilor you ran out of memory.

0
source

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


All Articles