假设我有一个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字典中吗?
非常感谢您的帮助。