views:

160

answers:

3

Does a method which I check for with respondsToSelector have to actually exist?

What if I only define it in the interface part and fail to implement it? I'm looking at a poor-man's virtual function in Objective-C.

+1  A: 

respondsToSelector will return NO, since the selector isn't callable at run-time. The interface part only affects compilation.

dorianj
+4  A: 

First, yes the method actually has to exist for the check to succeed in the context you describe. respondsToSelector: will return NO if the method is not implemented.

More importantly, I think you mean a poor man's pure virtual function in Objective-C. All instance methods are "virtual" in Objective-C; since method lookup is done a run-time, the subclass' implementation will always be used, even from a pointer of the superclass type. In Objective-C, there is no such thing as a pure virtual base class. You can often achieve what you want by either using a @protocol to define an API or using a base class that provides an implementation that throws an NSNotImplementedException as its body. Subclasses would obviously have to override the implementation, making it effectively pure virtual.

Barry Wark
Might want to edit the first line. Technically speaking, the methods does not have to exist. After all `respondsToSelector:` sole purpose is to determine whether a method does exist or not. It works fine with non-existant methods, it just returns no. I think you answer makes sense in the assumed context of the parent but for future readers you might want to make the distinction explicit.
TechZen
@TechZen Good point. Edited.
Barry Wark
+1  A: 

Given that calling respondsToSelector: only makes sense when you don’t know whether a method exists, it’s not entirely clear what you mean.

If you mean, does some implementation of a method with the specified selector have to exist somewhere, the answer is no. Selectors merely represent names of methods. The @selector directive doesn’t reference any aspect of any method implementation.

Ahruman