Lately I wrote an application in java (for android) which used reflection to invoke methods of some objects. The argument number and type was unknown, meaning, I had a unified mechanism that received an object name, method name and array of parameters (using JSON) and invoked the specified method on the specified object with an array of the arguments (Object[] filled with arguments of the required types).
Now I need to implement the same for iOS, I was able to invoke a selector when I knew the number of parameters the selector expected for like this:
SEL selector = NSSelectorFromString(@"FooWithOneArg");
[view performSelectorInBackground:selector withObject:someArg];
I know I can get the number of arguments the selector receives by using
int numberOfArguments = method_getNumberOfArguments(selector);
But is there a way to make a generic call like this:
[someObject performSelector:selector withObject:arrayOfObjects]
which is pretty much equivalent to Java's
someMethod.invoke(someObject, argumentsArray[]);
?
I want to avoid a switch case according to the amount of arguments the selector gets.
Sorry for the long dig, I just want to make my question as clear as possible.
Why not define each of your methods to take one argument: the array of objects? Presumably what you want is, with with the method
to invoke it with the parameters set from the array. Well, instead have:
then your whole dispatch mechanism just becomes:
With the awesome help here including the simple but perfect answer from user102008 I pulled together the following example. Note what I was really trying to do was allow someone to send me a target selector that either did or did not take an argument. If it takes an argument I assume they want the calling object's "self" returned as a reference:
Hope this helps someone digging around.
I modified @JustSid answer and added more validation, nil argument support, changed it to an Obj-C NSObject category method, and add
-performSelectorIfAvailable:
helper methods for easier use. Please enjoy! :)This small function should do the trick, its not perfect, but it gives you a starting point: