gpt4 book ai didi

javascript - 有没有办法将 JSValue 移动到新的 JSContext 中而忽略其原始上下文?

转载 作者:可可西里 更新时间:2023-11-01 05:54:43 27 4
gpt4 key购买 nike

我有两个 JSContext,我想不时地在它们之间交换 JSValue。但是,如果可能的话,我很难将 JSValue 移动到新上下文。

我正在尝试这个:

newContext[@"newValue"] = [JSValue valueWithObject:newValue inContext:newContext];

虽然新上下文现在具有该值,但该值仍保留其旧上下文。不幸的是,它仍然保留着它的旧语境。有什么建议吗?

最佳答案

我建议您在新上下文中创建新的 JSValue 之前,将 JSValue 的值从其旧的 javascript 上下文中提取到一个普通的 objective-c 对象中。查看 JSValue.h 表明 JSValue 类有一个只读属性,它保存值源自的 JSContext。

我无法从上面的代码中判断出你正在处理什么类型的值,但是例如(对于简单类型):

NSString *newString = [newValue toString]; // Extract from old JSValue
newContext[@"newValue"] = newString;

或者对于更复杂的对象:

@protocol MyPointExports <JSExport>
@property double x;
@property double y;
@end

@interface MyPoint : NSObject <MyPointExports>
// Put methods and properties not visible to JavaScript code here.
@end

newcontext[@"MyPoint"] = [MyPoint class]; // Define the class in Javascript

...

MyPoint *p = [newValue toObject]; // Extract from old JSValue
newContext[@"newValue"] = p;

请注意,该值仍将存在于旧的 JSContext 中(旧的 JSContext 将在保留旧值的同时保持事件状态)。您可能希望通过以下方式删除此引用:

oldContext[@"oldValue"] = nil; // Assuming the var in the oldContext was called oldValue

另请注意,您不需要使用构造函数:

+ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context;

因为 JavaScriptCore 具有以下内置转换(请参阅 JSValue.h):

  Objective-C type  |   JavaScript type
--------------------+---------------------
nil | undefined
NSNull | null
NSString | string
NSNumber | number, boolean
NSDictionary | Object object
NSArray | Array object
NSDate | Date object
NSBlock * | Function object *
id ** | Wrapper object **
Class *** | Constructor object ***

* Instances of NSBlock with supported arguments types will be presented to
JavaScript as a callable Function object. For more information on supported
argument types see JSExport.h. If a JavaScript Function originating from an
Objective-C block is converted back to an Objective-C object the block will
be returned. All other JavaScript functions will be converted in the same
manner as a JavaScript object of type Object.

** For Objective-C instances that do not derive from the set of types listed
above, a wrapper object to provide a retaining handle to the Objective-C
instance from JavaScript. For more information on these wrapper objects, see
JSExport.h. When a JavaScript wrapper object is converted back to Objective-C
the Objective-C instance being retained by the wrapper is returned.

*** For Objective-C Class objects a constructor object containing exported
class methods will be returned. See JSExport.h for more information on
constructor objects.

关于javascript - 有没有办法将 JSValue 移动到新的 JSContext 中而忽略其原始上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938576/

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