Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macos 使用JavaScriptCore更改JSContext传递的Swift对象_Macos_Swift_Osx Yosemite_Javascriptcore - Fatal编程技术网

Macos 使用JavaScriptCore更改JSContext传递的Swift对象

Macos 使用JavaScriptCore更改JSContext传递的Swift对象,macos,swift,osx-yosemite,javascriptcore,Macos,Swift,Osx Yosemite,Javascriptcore,我在更改传递到JavaScriptCore的对象时遇到问题 这是我的自定义对象,定义了一个名为testProperty的字符串属性: import Foundation import JavaScriptCore protocol JSCustomObjectExport: JSExport { var testProperty: String { get set } } class JSCustomObject: NSObject, JSCustomObjectExport {

我在更改传递到JavaScriptCore的对象时遇到问题

这是我的自定义对象,定义了一个名为testProperty的字符串属性:

import Foundation
import JavaScriptCore

protocol JSCustomObjectExport: JSExport {
    var testProperty: String { get set }
}

class JSCustomObject: NSObject, JSCustomObjectExport {
    var testProperty: String = "ABC"
}
这里是AppDelegate,我在其中创建了一个JSContext,将我的自定义对象传递给它,并运行一个JS脚本将其testProperty从“ABC”更改为“XYZ”。但是testProperty从未更改

import Cocoa
import JavaScriptCore

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var window: NSWindow!
    lazy var context = JSContext()

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        println("Started")
        var co = JSCustomObject()
        context.globalObject.setValue(co, forProperty: "customObject")
        context.evaluateScript("customObject.testProperty = 'XYZ'")
        println(co.testProperty) // ERROR(?): This prints "ABC" instead of "XYZ"
    }

}
我做错什么了吗?co.testProperty不应该更改吗


顺便说一句,这是一个OSX应用程序,在OSX 10.10.1上的XCode 6.1.1中编译。

似乎,它要求将协议标记为
@objc
,并且类具有显式的
@objc
导出名称

我在操场上试过下面的脚本,效果很好

import Foundation
import JavaScriptCore

@objc // <- HERE
protocol JSCustomObjectExport: JSExport {
    var testProperty: String { get set }
}

@objc(JSCustomObject) // <- HERE
class JSCustomObject: NSObject, JSCustomObjectExport {
    var testProperty: String = "ABC"
}

var context = JSContext()
var co = JSCustomObject()
context.globalObject.setValue(co, forProperty: "customObject")
context.evaluateScript("customObject.testProperty = 'XYZ'")
println(co.testProperty) // -> XYZ
<代码>导入基础 导入JavaScriptCore
@objc//帮助。在最新的xcode 7.2游乐场中,这将不再正常工作:(这将打印“ABC”而不是“XYZ”,这似乎是游乐场bug。仅当类和协议标记为公共并移动到游乐场源文件夹中的单独文件时,该示例在游乐场中也可以正常工作。