Skip to content

Instantly share code, notes, and snippets.

@boundsj
Created November 4, 2013 05:03
Show Gist options
  • Save boundsj/7298265 to your computer and use it in GitHub Desktop.
Save boundsj/7298265 to your computer and use it in GitHub Desktop.
JavaScriptCore, Objective-C calln' javascripts
var add2 = function() {
var two = 2;
return function(x) { return x + two; }
}
#import "ViewController.h"
@import JavaScriptCore;
@interface ViewController ()
@property (nonatomic, strong) JSContext *context;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
NSString *path = [[NSBundle mainBundle] pathForResource:@"amazeballs" ofType:@"js"];
NSString *amazeballs = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
[self.context evaluateScript:amazeballs];
}
- (IBAction)didTapaRunThaScriptz:(id)sender {
JSValue *add2 = [self.context[@"add2"] callWithArguments:@[]];
NSLog(@"================> result of add2(5) is %d", [[add2 callWithArguments:@[@5]] toInt32]);
NSLog(@"================> result of add2(10) is %d", [[add2 callWithArguments:@[@10]] toInt32]);
NSLog(@"================> result of add2(-10) is %d", [[add2 callWithArguments:@[@-10]] toInt32]);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment