gpt4 book ai didi

JavascriptCore 不从类中导出方法

转载 作者:搜寻专家 更新时间:2023-11-01 06:46:58 24 4
gpt4 key购买 nike

我正在尝试从 swift 类的单例实例中调用方法。

这是我的协议(protocol):

@objc public protocol MyProtocol: JSExport {

var name: String { get set }

func sum(a:Int, b: Int) -> Int
}

这是我的类(class):

private let sharedInstance = MySingleton()

@objc public class MySingleton: NSObject, MyProtocol {

// Singleton
public class var sharedApp : MySingleton {

return sharedInstance
}

public var username: String

override private init() {

self.username = "Oscar"

super.init()
}

public func sum(a: Int, b: Int) -> Int {

return a + b
}
}

我进行了一些测试。当我访问它传递的属性时:

func testName() {

var virtualMachine = JSVirtualMachine()
js = JSContext(virtualMachine: virtualMachine)

var singleton: MySingleton = MySingleton.sharedApp

self.context.setObject(
singleton.self,
forKeyedSubscript: "Singleton")

let name = js.evaluateScript("Singleton.username").toString()

XCTAssertTrue(name == "Oscar", "Name is not Colossal, was " + name); // PASS!!!!!
}

但是,当我调用一个方法时它失败了:

func testSum() {

var virtualMachine = JSVirtualMachine()
js = JSContext(virtualMachine: virtualMachine)

var singleton: MySingleton = MySingleton.sharedApp

self.context.setObject(
singleton.self,
forKeyedSubscript: "Singleton")

let name = js.evaluateScript("Singleton.sum(3, 2);").toInt32()

XCTAssertTrue(sum == 5, "Sum was " + String(sum)); // Fails. Says sum was 0
}

它仅在从 Javascript 对象读取/写入属性时有效,在调用方法时无效....

我做错了什么?

最佳答案

我刚刚找到了解决方案。试试这个。

func sum(a:Int, _ /* <-- make this argument unnamed */ b: Int) -> Int

JSExport 似乎还不支持命名参数。

关于JavascriptCore 不从类中导出方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29595190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com