So basically I'm implementing the typical way to handle JavaScript calls in objc using window.location="myobj:mymethod:myarg:myotherarg", however, I'm wondering if there is a way to apply an array of arguments to a method, similar to how you can in JavaScript.
Typically I've been doing
-(void) mymethod:(NSArray*) arr{
//method knows how many arguments it takes and what they mean at each index
}
I'd prefer to do:
-(void) mymethod:(NSString*) myarg myOtherArg: (NSString*) myotherarg{
//do stuff
}
and have a method like this:
+(void) callMethod:(NSString*)selectorName withArgs: (NSArray*)args onObject:(id) obj{
//implementation
}
[JEHelpers callMethod:selector withArgs:someArrayOfArgs onObject:myapp]
is this possible?
The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. Return Value: It returns the method values of a given function.
The Difference Between call() and apply()The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
The apply() method is an important method of the function prototype and is used to call other functions with a provided this keyword value and arguments provided in the form of array or an array like object. Array-like objects may refer to NodeList or the arguments object inside a function.
If you know that no method will take more than two arguments, you could use performSelector:withObject:withObject:
to do these calls. If the method takes less than two arguments, the unused withObject:
fields will be ignored.
+ (id)callMethod:(NSString *)selectorName withArgs:(NSArray *)args onObject:(id)obj {
id arg1 = nil, arg2 = nil;
if([args count]) {
arg1 = [args objectAtIndex:0];
if([args count] > 1])
arg2 = [args objectAtIndex:1];
}
return [obj performSelector:NSSelectorFromString(selectorName)
withObject:arg1 withObject:arg2];
}
If there could be more than two arguments, you will have to use NSInvocation
. This class lets you construct a message by passing the various arguments and defining the selector and object, then send the message and get the result.
+ (id)callMethod:(NSString *)selectorName withArgs:(NSArray *)args onObject:(id)obj {
SEL sel = NSSelectorFromString(selectorName);
NSMethodSignature *signature = [obj methodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:sel];
[invocation setTarget:obj];
NSUInteger index = 2;
for(id arg in args) {
[invocation setArgument:&arg atIndex:index];
++index;
}
id result;
[invocation setReturnValue:&result];
[invocation invoke];
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With