Skip to content

Instantly share code, notes, and snippets.

@bdash
Last active July 31, 2018 05:53
Show Gist options
  • Save bdash/8450420 to your computer and use it in GitHub Desktop.
Save bdash/8450420 to your computer and use it in GitHub Desktop.
Expose an Objective-C class to JavaScriptCore, with automatic JavaScript constructor generation.
// cc -framework JavaScriptCore -fobjc-arc -o javascriptcore-constructor-test javascriptcore-constructor-test.m
#include <JavaScriptCore/JavaScriptCore.h>
@protocol TestInterface <JSExport>
- (instancetype)initWithString:(NSString *)string;
@property (readonly) NSString *string;
@end
@interface TestClass : NSObject <TestInterface>
@end
@implementation TestClass
@synthesize string = _string;
- (instancetype)initWithString:(NSString *)string
{
if (!(self = [super init]))
return nil;
_string = [string copy];
return self;
}
@end
int main(int argc, char **argv)
{
JSContext *context = [[JSContext alloc] init];
context[@"TestClass"] = [TestClass class];
JSValue *result = [context evaluateScript:@"(new TestClass(\"Hello, world!\")).string"];
NSLog(@"Result: %@", result);
return 0;
}
@justbitguy
Copy link

It seems doesn't work in ios7.0.

@donpark
Copy link

donpark commented Oct 18, 2014

This works on iOS 7.1 and 8.0, outputing "Result: Hello, world!".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment