Should I use performSelector: when I also can call the method normally? - objective-c

I want to call a method on an object which I get through [self delegate]. I know which class it is so I can import the class and call it normally but I could also use performSelector: which doesn't require importing my class. I do not need to pass a parameter to the method. And yes, I did read this. Which one is preferable in this case?

Calling the method directly is more readable. performSelector: should be reserved for when you need higher order messaging.
Strictly speaking, you don't need to import the class to send it a message as message dispatch is dynamic rather than static, though you will get compile time warnings that the object may not respond to the selector.

Generally speaking, reflective operations, such as performSelector:, are less efficient than the direct ones. I have to admit that I am not very familiar with objC, though.

Related

Why would I use an NSInvocation instead of a Block?

Can someone offer a concrete reason for using an NSInvocation instead of just using a Block, or even a regular method call? I am finding descriptions of NSInvocation around the Web, but no examples of where it is vital to use or even the only good option.
NSInvocations and blocks can both be used to encapsulate a method call, along with arguments and a receiver that aren't defined until runtime. Before blocks existed, NSInvocation was the only way to do this. If that's all you need to do, blocks are a better bet. Uses of NSInvocation are quite rare these days.
However, unlike blocks, which can represent any amount of code along with captured values, an NSInvocation always represents a single method call.
This has some advantages:
Unlike blocks, which are opaque, an NSInvocation can be queried for the selector, the receiver, the arguments and the signature of the invoked method. If you receive an NSInvocation as an argument to a method (as with NSObject's -forwardInvocation), you can extract the arguments and call a different method instead.
An NSInvocation can be constructed for an arbitrary method call at runtime using -initWithMethodSignature:. If you wanted to implement an eval() function for Objective-C, for example, you'd use NSInvocation to actually invoke the methods.
NSInvocation allows you to dynamically at runtime construct and invoke an Objective-C message call, to a method that you may not know at compile-time, and it allows you to set the arguments using the information about the types and number of arguments from the signature of the method which again you may not know at runtime. (You may have a place that needs to be able to call different methods with different signatures, and pass different things depending on those signatures.) Thus it adds a level of dynamic-ness to the message passing mechanism. I am not sure how blocks relate to this.
NSInvocation is also used in -forwardInvocation: if you want your object to be able to handle arbitrary (not fixed at compile-time) messages, where the message dispatch system constructs an NSInvocation object describing the call and pass it to you, so that you can introspect and potentially modify the arguments and invoke it on another object or otherwise handle the information. This adds a lot of dynamic-ness in handling of messages at runtime. I also don't know how blocks relate to this.

Cast to (id) to call an arbitrary method in Objective-C

I have a situation when I need to call a method not necessarily supported by the object, but at the same time I can't use performSelector because it restricts the kind of arguments you can pass to the method. Hence I do this:
if ([someObject respondsToSelector:#selector(someMethod)])
[(id)someObject someMethod];
The compiler is happy, I am happy, but are there any caveats with this method of message sending?
What is the essential difference between the synchronous version of performSelector and the above?
Edit: is there a performance penalty with performSelector compared to the (id) method?
There are no special caveats here. By casting to id you are throwing away compiler-time checking, but you were doing that anyway with performSelector:.
Note that if you are using ARC the compiler will not let you do this unless it sees some implementation of someMethod.

Function call instead of self messaging — When to use what?

In Objective-C, when I want to call a subroutine, I send a message to an object, like:
[self mySubroutine:myParameter];
There is a (negligible?) performance penalty, so I could just use a C-style function call:
mySubroutine(myParameter);
The implementation of the latter would then reside outside the class’s #implementation context.
Is this a no-no? Is it common? Is there a best-practice on this?
Note that those are not necessarily equivalent. Since -mySubroutine is an instance method, it probably needs to access a given instance. In that case, your mySubroutine() function should have another parameter for the instance, too.
In general, use a method. If you’re worried about performance,1 you can always get an IMP to the method and use it as a function instead of the standard Objective-C message dispatch infrastructure.
That said, some disadvantages of using functions:
They cannot be overridden by subclasses;
There’s no introspection (when using the runtime to obtain a list of methods declared by an Objective-C class, functions aren’t enumerated);
They cannot be used as accessors/mutators of declared properties;
They aren’t visible to Key-Value Coding;
They cannot be directly used for Objective-C message forwarding;
They cannot be directly used in the various cases where a Cocoa API expects a selector (e.g. when using NSTimer).
Some advantages of using functions:
They cannot be overridden by subclasses (if you want to prevent this);
There’s no introspection (if you want to prevent this);
They can be inlined;
They can have file scope (static), preventing code from other files from accessing them.
1When you’ve determined that the message dispatch infrastructure is actually a bottleneck. This does happen; for instance, some Apple audio examples do not use Objective-C for audio processing.
Edit: Based on OP’s comment, another advantage of functions is that they aren’t necessarily related to a class. If the computation of an approximate value for the sine of an angle doesn’t depend on an Objective-C instance, there’s no need to make it a method — a function is a better fit.
It might be worth using where you have static utility functions, such as in a maths library.
In general though, if you need methods that act on the state of an object, the C approach won't be much use, as you won't have implicit access to self, unless you explicitly pass it as a parameter.
You may also run into namespace issues. With the Objective-C different classes can share method names, with the c approach all your functions will need different signatures.
Personally I would always use objective-c methods, the performance difference will be negligible.

How can I tell the compiler that my class resolves methods dynamically?

I have a class which uses resolveInstanceMethod to dynamically implement methods.
When I call the dynamically implemented methods from other parts of the code, the compiler emits a warning that the object may not respond to the selector. I would like the compiler to not emit such warnings for this class, but I don't want to suppress warnings when I invoke an invalid selector on other classes. Is this possible?
Assuming you know the method signatures that will be dynamically resolved at compile time, you can declare 'em in an informal category:
#interface MyDynamicallyResolvingClass(MethodsThatWillResolveAtRuntime)
... declare the methods here ...
#end
No need to provide an implementation.
If you don't know the signatures -- if the method names are dynamic, too -- then you'll need to use either -performSelector: (or the single or double object argument variants) or you will likely want to use NSInvocation, unless performance is a major concern (if it is, there are alternative solutions that are significantly more fiddly).
Use performSelector:
It's equivalent to sending a message directly to the receiver, however, it allows you to send messages that aren’t determined until runtime.
If your methods take one or two arguments, you can use the sisters of this method: – performSelector:withObject: and – performSelector:withObject:withObject:
If your methods have more than two arguments, or arguments that are not of object type, this answer is not adapted.

Does the respondsToSelector method have to exist?

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.
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.
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.
respondsToSelector will return NO, since the selector isn't callable at run-time. The interface part only affects compilation.