简体   繁体   中英

JavaScriptCore: Trying to pass JS function as block to Objective-C, Getting 'TypeError' Exception

I've been playing around with the new iOS 7/Mavericks JavascriptCore bridge, trying to get JS functions on Objective-C as blocks.

The JavascriptCore header files states that this is possible as long as every argument is supported, but trying this:

JSContext *context = [[JSContext alloc] init];

context[@"Log"] = ^(NSString *message){NSLog(@"%@", message);};

context[@"BlockTest"] = ^(void (^blockTest)(NSString* blockString)){
    NSLog(@"Calling Block Test");
    blockTest(@"STRINGGGGG");
};

[context evaluateScript:@"BlockTest( function(dataString){Log('JS '+dataString);} )"];

raises the following JS exception:

TypeError: '[object NSBlock]' is not a function (evaluating 'BlockTest( function(dataString){Log('JS '+dataString);} )')

Any ideas on what's wrong with my test code?

I know that you've accepted the answer that support for this was removed (and that this is an old question), but you can pass a JS function as a block to Objective-C in the JavaScriptCore framework introduced with iOS7/Mavericks - your code just needs to change slightly how you declare and invoke the block:

JSContext *context = [[JSContext alloc] init];

context[@"Log"] = ^(NSString *message){NSLog(@"%@", message);};

context[@"BlockTest"] = ^(JSValue *blockTest){
    NSLog(@"Calling Block Test");
    [blockTest callWithArguments:@[@"STRINGGGGG"]];
};

[context evaluateScript:@"BlockTest( function(dataString){Log('JS '+dataString);} )"];

Seems like support for this was removed and documentation not updated:

http://trac.webkit.org/changeset/144489

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM