如何将JSValueRef从Objective-C转换为JavaScript变量
使用JavaScriptCore,如果我在Objective-C中有一个NSString,如下所示:如何将JSValueRef从Objective-C转换为JavaScript变量,objective-c,ios,cocoa-touch,javascriptcore,Objective C,Ios,Cocoa Touch,Javascriptcore,使用JavaScriptCore,如果我在Objective-C中有一个NSString,如下所示: NSString *objcName = @"Kristof"; 和一个名为jsContextRef的JSGlobalContextRef上下文 如何将objcName的Objective-C值转换为jsContextRef中的命名JavaScript变量?我的思路是: JSStringRef jsNameRef = JSStringCreateWithUTF8CString([objcNam
NSString *objcName = @"Kristof";
和一个名为jsContextRef的JSGlobalContextRef上下文
如何将objcName的Objective-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);
我在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 );
}
这似乎奏效了