如何将JSValueref传输到来自Objective-C的JavaScript Var
-
12-12-2019 - |
题
使用javascriptcore,如果我在目标-c中有nsstring:
NSString *objcName = @"Kristof";
.
和jsglobalcontextref上下文,称为 jscontextref 。
如何将objcname的Object-C值转移到JSContExtref中的名为JavaScript变量中?我正在沿着:
JSStringRef jsNameRef = JSStringCreateWithUTF8CString([objcName UTF8String]);
JSValueRef jsValueRef = JSValueMakeString(jsContextRef, jsNameRef);
.
让我们说变量名将是“jsname”。我需要几个电话(或甚至一个电话),这样的话:
// This part is pseudo-code for which I would like to have proper code:
JSValueStoreInVarWithName(jsContextRef,"jsName",jsValueRef);
.
因此,最终将在Objective-C中的调用时正确评估此JavaScript:
NSString *lJavaScriptScript = @"var jsUppercaseName = jsName.toUpperCase();";
JSStringRef scriptJS = JSStringCreateWithUTF8CString([lJavaScriptScript UTF8String]);
JSValueRef exception = NULL;
JSValueRef result = JSEvaluateScript(jsContextRef, scriptJS, NULL, NULL, 0, &exception);
. 解决方案
我在 javascriptcoreheadstart的示例代码中的,更具体地是jswrappers.m文件。它有这种方法:
/* -addGlobalStringProperty:withValue: adds a string with the given name to the
global object of the JavaScriptContext. After this call, scripts running in
the context will be able to access the string using the name. */
- (void)addGlobalStringProperty:(NSString *)name withValue:(NSString *)theValue {
/* convert the name to a JavaScript string */
JSStringRef propertyName = [name jsStringValue];
if ( propertyName != NULL ) {
/* convert the property value into a JavaScript string */
JSStringRef propertyValue = [theValue jsStringValue];
if ( propertyValue != NULL ) {
/* copy the property value into the JavaScript context */
JSValueRef valueInContext = JSValueMakeString( [self JSContext], propertyValue );
if ( valueInContext != NULL ) {
/* add the property into the context's global object */
JSObjectSetProperty( [self JSContext], JSContextGetGlobalObject( [self JSContext] ),
propertyName, valueInContext, kJSPropertyAttributeReadOnly, NULL );
}
/* done with our reference to the property value */
JSStringRelease( propertyValue );
}
/* done with our reference to the property name */
JSStringRelease( propertyName );
}
}
.
这正是我需要的。JSStringValue方法的代码在同一项目中的NSStringwrAppers.m中,是:
/* return a new JavaScriptCore string value for the string */
- (JSStringRef)jsStringValue {
return JSStringCreateWithCFString( (__bridge CFStringRef) self );
}
.
不隶属于 StackOverflow