A JSVirtual instance represents a self-contained environment for JavaScript execution. You use this class for two main purposes: to support concurrent JavaScript execution, and to manage memory for objects bridged between JavaScript and Objective-C or Swift.
SDKs
- iOS 7.0+
- macOS 10.9+
- tvOS 9.0+
Framework
- JavaScriptCore
Overview
Threading and Concurrent JavaScript Execution
Each JavaScript context (a JSContext object) belongs to a virtual machine. Each virtual machine can encompass multiple contexts, allowing values (JSValue objects) to be passed between contexts. However, each virtual machine is distinct—you cannot pass a value created in one virtual machine to a context in another virtual machine.
The JavaScriptCore API is thread safe—for example, you can create JSValue objects or evaluate scripts from any thread—however, all other threads attempting to use the same virtual machine will wait. To run JavaScript concurrently on multiple threads, use a separate JSVirtual instance for each thread.
Managing Memory for Exported Objects
When you export an Objective-C or Swift object to JavaScript, you must not to store JavaScript values in that object. This action creates a retain cycle—JSValue objects hold strong references to their enclosing JavaScript contexts, and JSContext objects hold strong references to the native objects you export to JavaScript. Instead, use use the JSManaged class to conditionally retain a JavaScript value, and report the native ownership chain for that managed value to the JavaScriptCore virtual machine. Use the add and remove methods to describe your native object graph to JavaScriptCore. After you remove the last managed reference for an object, that object can be safely destroyed by the JavaScript garbage collector.