Como transferir um JSValueRef para uma var JavaScript do Objective-C
-
12-12-2019 - |
Pergunta
Usando JavaScriptCore, se eu tiver um NSString em Objective-C assim:
NSString *objcName = @"Kristof";
e um contexto JSGlobalContextRef chamado jsContextRef.
Como transfiro o valor Objective-C de objcName para uma variável JavaScript nomeada no jsContextRef?Eu estava pensando na seguinte linha:
JSStringRef jsNameRef = JSStringCreateWithUTF8CString([objcName UTF8String]);
JSValueRef jsValueRef = JSValueMakeString(jsContextRef, jsNameRef);
Digamos que o nome da variável seja “jsName”.Preciso de mais algumas ligações (ou talvez até uma ligação), algo como:
// This part is pseudo-code for which I would like to have proper code:
JSValueStoreInVarWithName(jsContextRef,"jsName",jsValueRef);
para que no final este JavaScript seja avaliado corretamente quando chamado assim em 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);
Solução
Encontrei a resposta no código de amostra para JavaScriptCoreHeadstart, mais especificamente o arquivo JSWrappers.m.Tem este método:
/* -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 );
}
}
que é exatamente o que eu precisava.O código para o método jsStringValue está em NSStringWrappers.m no mesmo projeto e é:
/* return a new JavaScriptCore string value for the string */
- (JSStringRef)jsStringValue {
return JSStringCreateWithCFString( (__bridge CFStringRef) self );
}
Isso parece funcionar.