2012-10-02 3 views
0

에서 자바 스크립트 VAR에 JSValueRef를 전송합니다.어떻게이 같은 목표 - C에 내가있는 NSString이있는 경우, JavaScriptCore는 사용 목적-C

objcName의 Objective-C 값을 jsContextRef의 명명 된 JavaScript 변수로 어떻게 전송합니까?

JSStringRef jsNameRef = JSStringCreateWithUTF8CString([objcName UTF8String]); 
JSValueRef jsValueRef = JSValueMakeString(jsContextRef, jsNameRef); 

변수 이름이 "jsName"이라고 가정 해 봅시다.

NSString *lJavaScriptScript = @"var jsUppercaseName = jsName.toUpperCase();"; 
JSStringRef scriptJS = JSStringCreateWithUTF8CString([lJavaScriptScript UTF8String]); 
JSValueRef exception = NULL; 
JSValueRef result = JSEvaluateScript(jsContextRef, scriptJS, NULL, NULL, 0, &exception); 

답변

1

: 그래서 목표 - C에서 다음과 같이 호출 할 때 결국이 자바 스크립트를 제대로 평가하는 것이다

// This part is pseudo-code for which I would like to have proper code: 
JSValueStoreInVarWithName(jsContextRef,"jsName",jsValueRef); 

: 나는 (어쩌면 심지어 하나의 호출) 몇 가지 더 많은 통화와 같은 뭔가가 필요 sample code for 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); 
} 

이 코드는 작동하는 것 같습니다.