jsvalueref를 JavaScript var로 전송하는 방법 objective-c
-
12-12-2019 - |
문제
javascriptcore를 사용하여 objective-c에서 nsString이있는 경우 :
NSString *objcName = @"Kristof";
.
및 jsglobalcontextref 컨텍스트가 jscontextref 이라는 을 나타냅니다.
objcname의 obsive-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);
.
이 JavaScript가 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);
. 해결책
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