respondsToSelector returns YES for "setTitle:" on UIButton but there is no such selector

160 Views Asked by At

I'm using respondsToSelector: and most of the time it works fine. But there is one case in which I get wrong result:

UIButton* button = [[UIButton alloc] init];
if([button respondsToSelector:NSSelectorFromString(@"setTitle:")]) // returns YES
{
    // try to call "setTitle:"
}

respondsToSelector: returns YES but there is no setTitle: selector in UIButton class. There is setTitle:forState: selector but this is definitely not the same.

So why does respondsToSelector: return YES?

2

There are 2 best solutions below

0
Wain On BEST ANSWER

Responds to selector doesn't just check the public interface, it'll take any method it can find. I don't recall if the early API for UIButton ever exposed the title directly, but internally it's likely called as the state changes.

Try to only use respondsToSelector: for API that you actually need to verify exists, and note that there is often private API which is later made public and that this can also cause interesting situations...

0
iCoder On

Alexandr, You should use this "respondsToSelector" method only when you want to check if an object implements the method you are about to call. And for setting Button Title, why you are required to use this ??

You should use this method generally you are working with custom delegate methods..