2016-02-24 143 views
1

我有一个JSExport协议,其名称为ChannelExport,方法为- (void)sendRequest:(NSDictionary *)request withCallback:(JSValue *)callback;。从JavaScript调用代码这种方法可行好吧,是这样的:如何将JS函数作为对象属性传递给iOS

channel.sendRequestWithCallback({'foo': 'bar'}, function(response) { ... }); 

在ObjC,我可以访问值在request词典,又拨打了callback功能。

现在我想的界面更改为- (void)sendRequest:(NSDictionary *)request,传递JS函数作为request字典的一部分,就像这样:

channel.sendRequestWithCallback({ 
    'foo': 'bar' 
    'callback': function(response) { ... } 
}); 

在这种情况下,当我尝试调用callback功能ObjC,应用程序崩溃。显然callback对象不是JSValue,而是NSDictionary(更准确地说,是__NSDictionaryM)。我假设JS函数被正确包装为JSValue,就像将它作为简单参数传递一样。

任何暗示为什么会发生这种情况,以及如何解决这个问题?

回答

1

您不能使用- (void)sendRequest:(NSDictionary *)request签名来实现您的目标。如果将参数定义为NSDictionary,JavaScriptCore将递归地将此字典中的所有对象转换为相应的Objective-C对象。改为使用- (void)sendRequest:(JSValue *)requestValue

- (void)sendRequest:(JSValue *)requestValue { 
    JSValue *fooJSValue = [requestValue valueForProperty:@"foo"]; 
    NSString *bar = [fooJSValue isUndefined] ? nil : fooValue.toString; 
    // use bar 

    JSValue *callback = [requestValue valueForProperty:@"callback"]; 
    [callback callWithArguments:myArguments]; 
} 
相关问题