壹個 JSVirtualMachine 實例代表壹個執行 JavaScript 的自包含(self-contained)的環境。妳可以用這個類做兩件事情:① JavaScript 的並發執行;② 橋接 JavaScript 和 Objective-C 或 Swift 的對象的內存管理。
每壹個 JavaScript 上下文(也就是壹個 JSContext 對象)歸屬於壹個虛擬機。每壹個虛擬機可以包含多個不同的上下文(context),而且可以在不同的上下文(context)之間傳值( JSValue 對象)。但是,每壹個虛擬機都是獨立的——妳不能將在壹個虛擬機中創建的值傳到另壹個虛擬機的壹個上下文中。
JavaScriptCore 的 API 是線程安全的。比如,妳可以在任壹線程中創建 JSValue 對象或者執行 scripts,但是,想要使用同壹個虛擬機的所有其他線程都需要等待。如果要在多條不同線程上並發執行 JavaScript ,那麽妳就要確保每壹條線程使用的 JSVirtualMachine 實例都是獨立的。
當妳將壹個 Objective-C 或者 Swift 對象轉成 JavaScript時,妳壹定不要在那個對象中存儲 JavaScript 值。否則,這將導致循環引用—— JSValue 對象對它們的封閉的 JavaScript 上下文進行了強引用, 而 JSContext 又對要被轉成 JavaScript 的原生對象進行了強引用。 妳應該用 JSManagedValue 類有條件地持有(retain)壹個 JavaScript 值,並且為 managed value向 JavaScriptCore 虛擬機說明原生的擁有關系鏈(ownership chain)。使用 addManagedReference:withOwner: 和 removeManagedReference:withOwner: 方法向 JavaScriptCore 描述妳的原生對象圖(object graph)。在妳移除了壹個對象的最後壹個 managed reference 後,那個對象將會被 JavaScript 垃圾回收器(garbage collector)安全銷毀。
Initializes a JavaScript virtual machine.
Declaration
Return Value
A new, independent JavaScript virtual machine.
Discussion
Use this initializer to create a virtual machine for use with more than one JavaScript context. By default, creating a JSContext object automatically creates an independent virtual machine—to share a virtual machine between contexts, obtain a JSVirtualMachine instance and then create contexts using the initWithVirtualMachine: initializer.
Availability
Available in iOS 7.0 and later.
Notifies the JavaScriptCore virtual machine of an external object relationship.
Declaration
Parameters
Discussion
Use this method to make the JavaScript runtime aware of arbitrary external Objective-C or Swift object graphs. The runtime can then use this information to retain any JavaScript values that are referenced from somewhere in said object graph.
For correct behavior, clients must make their external object graphs reachable from within the JavaScript runtime. If an Objective-C or Swift object is reachable from within the JavaScript runtime, all managed references transitively reachable from it as recorded using the addManagedReference:withOwner: method are scanned by the garbage collector.
Availability
Available in iOS 7.0 and later.
Notifies the JavaScriptCore virtual machine that a previously registered object relationship no longer exists.
Declaration
Parameters
Discussion
Use this method to deregister object relationships recorded using the removeManagedReference:withOwner: method.
The JavaScript garbage collector continues to scan any references that were reported to it until you use this method to remove those references.
Availability
Available in iOS 7.0 and later.
JSVirtualMachine 在內存管理中扮演了什麽樣的角色?