Come trasferire un jsvalueref in un var javascript da Objective-C
-
12-12-2019 - |
Domanda
Usando JavaScriptCore, se ho un NSString in Objective-C come questo:
NSString *objcName = @"Kristof";
.
e un contesto JsgrobalConTextref chiamato jscontextref .
Come trasferisco il valore dell'obiettivo-c di objcname in una variabile JavaScript denominata nel jsconTextref?Stavo pensando lungo le linee di:
JSStringRef jsNameRef = JSStringCreateWithUTF8CString([objcName UTF8String]);
JSValueRef jsValueRef = JSValueMakeString(jsContextRef, jsNameRef);
.
Diciamo che il nome della variabile sarà "jsname".Ho bisogno di un paio di chiamate più chiamate (o forse anche una chiamata), qualcosa del genere come:
// This part is pseudo-code for which I would like to have proper code:
JSValueStoreInVarWithName(jsContextRef,"jsName",jsValueRef);
.
In modo che alla fine questo JavaScript valuterà correttamente quando viene chiamato come questo in Objective-C:
NSString *lJavaScriptScript = @"var jsUppercaseName = jsName.toUpperCase();";
JSStringRef scriptJS = JSStringCreateWithUTF8CString([lJavaScriptScript UTF8String]);
JSValueRef exception = NULL;
JSValueRef result = JSEvaluateScript(jsContextRef, scriptJS, NULL, NULL, 0, &exception);
. Soluzione
Ho trovato la risposta in codice di esempio per javascriptcoreheadstart , più specificamente il file jswrappers.m.Ha questo metodo:
/* -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 );
}
}
.
/* return a new JavaScriptCore string value for the string */
- (JSStringRef)jsStringValue {
return JSStringCreateWithCFString( (__bridge CFStringRef) self );
}
.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow