如何在Javascript中显示数组的内容。该数组存在于ObjectiveC代码中

时间:2011-09-05 09:01:29

标签: javascript html objective-c xcode

如何在Javascript中显示数组的内容。该数组存在于ObjectiveC代码

以下是Objective C Code,

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"Array"ofType:@"html"]isDirectory:NO]]];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"Example" ofType:@"csv"];
        NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
        NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n,"]];
        for (NSString* line in lines) {

                 NSLog(@"%@", line);


                }
                NSLog(@" %d", [lines count]);

那么如何将这个.m文件链接到Html或Javascript,以便我可以在OnClick of Button上显示数组的内容。这个问题可能很简单。但我是javascript和Html的新手,所以我不知道用什么标签或代码来链接.m文件和Html文件。

1 个答案:

答案 0 :(得分:0)

如果你不了解HTML和JavaScript,那真的超出了这个问题,你必须学习两者,然后再回到Cocoa。

一旦你知道了(你已经在JavaScript中学习了dom操作),你可以使用这样的东西做你想做的事情:

function showArrayContents( array ) {
  // do something in JavaScript here to show the array
}

在Objective-C上,你可以像这样调用这个函数:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"Array"ofType:@"html"]isDirectory:NO]]];

NSString *path = [[NSBundle mainBundle] pathForResource:@"Example" ofType:@"csv"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n,"]];    

// this is where you call the JS function above

WebScriptObject * scriptObject = [ webView windowScriptObject ];
[scriptObject callWebScriptMethod: @"showArrayContents" withArguments: [NSArray arrayWithObject: withArguments ]]