在objective-c中是否有JavaScript应用方法?

Jes*_*rle 5 javascript cocoa objective-c

所以基本上我正在使用window.location ="myobj:mymethod:myarg:myotherarg"来实现在objc中处理JavaScript调用的典型方法,但是,我想知道是否有办法将一个参数数组应用于一个方法,类似于你在JavaScript中的方式.

通常我一直在做

-(void) mymethod:(NSArray*) arr{
    //method knows how many arguments it takes and what they mean at each index
}
Run Code Online (Sandbox Code Playgroud)

我更愿意这样做:

-(void) mymethod:(NSString*) myarg myOtherArg: (NSString*) myotherarg{
    //do stuff
}
Run Code Online (Sandbox Code Playgroud)

并有一个这样的方法:

+(void) callMethod:(NSString*)selectorName withArgs: (NSArray*)args onObject:(id) obj{
    //implementation
}
[JEHelpers callMethod:selector withArgs:someArrayOfArgs onObject:myapp]
Run Code Online (Sandbox Code Playgroud)

这可能吗?

ugh*_*fhw 2

如果您知道没有方法会接受两个以上的参数,则可以使用performSelector:withObject:withObject:来执行这些调用。如果该方法采用的参数少于两个,则未使用的withObject:字段将被忽略。

+ (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];
}
Run Code Online (Sandbox Code Playgroud)

如果可能有两个以上的参数,则必须使用NSInvocation. 此类允许您通过传递各种参数并定义选择器和对象来构造消息,然后发送消息并获取结果。

+ (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;
}
Run Code Online (Sandbox Code Playgroud)