ios - JSExport 一个多参数的 Objective-C 方法不能吗?

标签 ios objective-c javascriptcore

考虑一下:

@protocol FooExport <JSExport>
- (void)method1:(NSString *)param1;
- (void)method2:(NSString *)param1 param2:(NSString *)param2;
@end

@interface Foo : NSObject <FooExport>
@end

@implementation Foo
- (void)method1:(NSString *)param1 {
    NSLog(@"method1");
}
- (void)method2:(NSString *)param1 param2:(NSString *)param2 {
    NSLog(@"method2");
}
@end

{
    sContext = [[JSContext alloc] init];
    if (sContext)
    {
        sContext[@"foo"] = [[Foo alloc] init];
        [sContext evaluateScript:@"foo.method1(\"foo\");"]; // method1 is called
        [sContext evaluateScript:@"foo.method2(\"foo\", \"bar\");"]; // method2 is NOT called
    }
}

方法 1 被调用得很好,但方法 2 从未被调用。

如果我按如下方式更改 method2:

@protocol FooExport <JSExport>
- (void)method1:(NSString *)param1;
- (void)method2:(NSString *)param1;
@end

method2 现在通过 [sContext evaluateScript:@"foo.method2(\"foo\",\"bar\");"]; (我必须通过 JSContext.currentArguments 挖掘出第二个参数)。

同样,如果我按如下方式更改 method2:

@protocol FooExport - (void)method1:(NSString *)param1; - (无效)方法 2; @结束

method2 再次通过 [sContext evaluateScript:@"foo.method2(\"foo\",\"bar\");"]; (而且我必须通过 JSContext.currentArguments 挖掘出这两个参数)。

这是设计使然吗? JSContext.currentArguments 的缺点是我必须处理 JSValues 而不是已经转换的 Objective-C 类型。

最佳答案

快速阅读 JSContext.h 会发现这颗 gem :

// When a selector that takes one or more arguments is converted to a JavaScript
// property name, by default a property name will be generated by performing the
// following conversion:
//  - All colons are removed from the selector
//  - Any lowercase letter that had followed a colon will be capitalized.
// Under the default conversion a selector "doFoo:withBar:" will be exported as
// "doFooWithBar". The default conversion may be overriden using the JSExportAs
// macro, for example to export a method "doFoo:withBar:" as "doFoo":
//
//    @protocol MyClassJavaScriptMethods <JSExport>
//    JSExportAs(doFoo,
//    - (void)doFoo:(id)foo withBar:(id)bar
//    );
//    @end
//
// Note that the JSExport macro may only be applied to a selector that takes one
// or more argument.
#define JSExportAs(PropertyName, Selector) \
    @optional Selector __JS_EXPORT_AS__##PropertyName:(id)argument; @required Selector

关于ios - JSExport 一个多参数的 Objective-C 方法不能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23276548/

相关文章:

javascript - 每次调用时都会重新创建 JavaScript 函数内部的数组吗?

ios - 在 UINavigationController 中覆盖向后滑动手势

iphone - 有没有办法在 iOS 中使用 sip 进行视频聊天(双向)?

objective-c - 将 Swift 3 升级到 4, objective-c 中不再有 swift 扩展

ios - NSString 中的内存泄漏 stringWithUTF8String : with ARC enabled

javascript - UIWebView JavaScript 丢失对 iOS JSContext 命名空间(对象)的引用

ios - 如何推迟处理正在运行的 iOS 应用程序中的推送通知?

java - Selendroid "Error forwarding the new session cannot find : Capabilities"

ios - 检测 Swift 2 中一个节点的子节点和另一个节点的碰撞

ios7 - 如果无法访问 UIWebView 的运行时,为什么要在 iOS7 中使用 JavaScriptCore?