2011年10月29日土曜日

Sample: WebScriptObject ( Javascript associative array ) to NSDictionary ( WebScriptObject ( Javascript array ) to NSArray )

Addtion(20111029T2300): Nest Version



SampleAppDelegate.h

#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
@interface SampleAppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
}

@property (assign) IBOutlet NSWindow *window;

@end

SampleAppDelegate.m

#import "SampleAppDelegate.h"
@implementation SampleAppDelegate
@synthesize window;
+ (NSArray *)arrayWithWebScriptObject:(WebScriptObject *)obj
{
NSMutableArray *ret = [NSMutableArray array];
NSUInteger count = [[obj valueForKey:@"length"] integerValue]; //exception occurs if it is associative array.
unsigned i;
for (i = 0; i < count; i++) {
[ret addObject:[obj webScriptValueAtIndex:i]];
}
return [[ret retain] autorelease];
}
+ (NSDictionary *)dictionaryWithWebScriptObject:(WebScriptObject *)obj
webScriptObject:(WebScriptObject *)scriptObj
{
NSMutableDictionary *ret= [NSMutableDictionary dictionary];
id keys= [scriptObj callWebScriptMethod:@"_f0_"
withArguments:[NSArray arrayWithObjects:obj, nil]];
NSArray *keyAry= [SampleAppDelegate arrayWithWebScriptObject:keys];
unsigned i;
for(i= 0; i<[keyAry count]; i++) {
NSString *key= [keyAry objectAtIndex:i];
[ret setObject:[obj valueForKey:key] forKey:key];
}
return [[ret retain] autorelease];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
WebView *webView = [[WebView alloc] init];
[[webView mainFrame] loadHTMLString:@"" baseURL:NULL];
WebScriptObject *scriptObject = [webView windowScriptObject];

NSString *_f0_= @"function _f0_(hash){var ret=[];for(var key in hash){ret.push(key);}return ret;}";
NSString *code= @"function main(){return {'key0':'val0', 'key1':'val1'};}";
NSString *script = [NSString stringWithFormat:@"try { %@ %@ } catch (e) { e.toString() }", code, _f0_];
id ret0= [scriptObject evaluateWebScript:script];
if (![ret0 isMemberOfClass:[WebUndefined class]]) {
NSLog(@"ret(main): %@", ret0);
}

id ret= [scriptObject callWebScriptMethod:@"main" withArguments:nil];
if (ret && [ret isMemberOfClass:[WebScriptObject class]]) {
WebScriptObject *obj= (WebScriptObject *)ret;
NSDictionary *dict= [SampleAppDelegate dictionaryWithWebScriptObject:obj
webScriptObject:scriptObject];
NSLog(@"%@", dict);
}
}
@end


reference: "Notes on Cocoa - Convert a Javascript array to an NSArray"

0 件のコメント: