假設我有一個JavaScript文件javascript.js
,其中包含以下內容。如何使用JavaScriptCore將JavaScript對象轉換爲NSDictionary
window.fruitsAndVeggies = {
name2CategoryMap: {
"apple": "fruit",
"carrot": "vegetable"
}
}
誰能告訴我獲得Javascript對象window.fruitsAndVeggies
的內容到一個NSDictionary最簡單的方法?
來自互聯網上的各種來源,我將以下片段拼湊在一起,創建一個Javascript上下文,然後評估該上下文中的JavaScript代碼。
JSGlobalContextRef ctx = JSGlobalContextCreate(NULL); // create context
JSValueRef exception = JSValueMakeUndefined(ctx); // create object to hold exceptions
// Make a "window" object in the JS Context
JSStringRef makeWindowScript = JSStringCreateWithUTF8CString("var window = {}");
JSValueRef result = JSEvaluateScript(ctx, makeWindowScript, NULL, NULL, 0, &exception);
// load the javascript file into an NSString
NSBundle * bundle = [NSBundle bundleWithIdentifier:@"my.bundle"];
NSString *filePath = [bundle pathForResource:@"javascript" ofType:@"js"];
NSError *error;
NSString *stringFromFile = [[NSString alloc]
initWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
// convert NSString to a JSStringRef
CFStringRef cfString = (__bridge CFStringRef)stringFromFile;
JSStringRef jsString = JSStringCreateWithCFString(cfString);
// evaluate the javascript
JSEvaluateScript(ctx, jsString, NULL, NULL, 0, &exception);
我很困惑接下來該做什麼。我需要在我的objective-c代碼中使用fruitsAndVeggies.name2CategoryMap
的內容。訪問它們的最簡單方法是什麼?有一個簡單的函數可以調用它們將它們加載到Objective-C字典中嗎?
非常感謝您的幫助。