1.8 Invoking the Selectors of an Object Dynamically
Problem
You want to be able to dynamically call any method in any object given the name of
the method and its parameters.
Solution
Use the NSInvocation class, like so:引自第25页
Discussion
Objective-C is so dynamic that you can invoke a method in another object just by
knowing the name of that object, the name of the method, and its parameters. Then
you can form a selector out of the method name and parameters, form a method signature,
and assign parameters to that invocation. Eventually you can, depending on
how your method is defined, attempt to fetch the return value of that method as well.
NSInvocation, used in this recipe, is not the optimal way of invoking a method in another object. This technique is usually used when you want to forward a method invocation
to another object. NSInvocation is also useful if you are constructing and calling selectors
dynamically and on the fly for dynamic methods. However, for an average iOS
application, you probably will not need to use such a dynamic mechanism to call
methods on an object.
To do this, you need to follow these steps:
1. Form a SEL value using the name of the method and its parameter names (as
explained in Recipe 1.7).
2. Form a method signature of type NSMethodSignature out of your SEL value.
3. Form an invocation of type NSInvocation out of your method signature.
4. Tell the invocation what object you are targeting.
5. Tell the invocation what selector in that object you want to invoke.
6. Assign any arguments, one by one, to the invocation.
7. Invoke the method using the invocation object and demand a return value (if any).
After calling the invokeMyMethodDynamically method, as seen in this recipe’s Solution,
we will observe the following values printed in the console window:引自第25页
Param 1 = First Parameter
Param 2 = 102
Return Value = Objective-C