2012-10-02 25 views
0

使用的JavaScriptCore轉移到一個JavaScript變種,如果我有一個NSString在Objective-C是這樣的:如何將JSValueRef從Objective-C的

NSString *objcName = @"Kristof"; 

和JSGlobalContextRef上下文調用jsContextRef

如何將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); 

回答

1

我在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); 
} 

這似乎是工作。