Objective c Swift 3通过选择器将闭包传递给objc函数
我想通过选择器将闭包传递给另一个函数。以下是我在理想情况下努力做到的:Objective c Swift 3通过选择器将闭包传递给objc函数,objective-c,swift,function,closures,selector,Objective C,Swift,Function,Closures,Selector,我想通过选择器将闭包传递给另一个函数。以下是我在理想情况下努力做到的: @objc private func aFunction(_ firstParam: String, onComplete: (String) -> Void) { //..some internal codes onComplete("Done.") } func functionCaller(_ selectorString: String, paramString: String, onComp
@objc private func aFunction(_ firstParam: String, onComplete: (String) -> Void) {
//..some internal codes
onComplete("Done.")
}
func functionCaller(_ selectorString: String, paramString: String, onComplete: (String) -> Void) {
let selector : Selector = NSSelectorFromString(selectorString)
self.perform(selector, with: printString, with: onComplete)
}
functionCaller("aFunction:onComplete:", paramString: "anotherParameter", onComplete: { (_ myString String) -> Void in
print(myString)
})
这里的问题是,当您试图编译此文件时,Swift会给出一个名为“分段错误:11”的错误
我发现有问题的一行是:
self.perform(选择器,带:printString,带:onComplete)
当我将lastwith:onComplete
参数更改为字符串(也更改了相关函数参数)时,它正在工作。据我所知,问题是通过self.perform
调用发送闭包不起作用,因为第一个函数是带有'@objc'标记的函数(我之所以这样做,是因为在Swift 3上执行选择器不起作用)
那么,你知道如何通过执行选择器将函数或闭包传递到带有'@objc'标记的函数中吗?尝试在函数中使用
any
而不是String
func functionCaller(_ selectorString: String, paramString: String, onComplete: (Any) -> Void) {
let selector : Selector = NSSelectorFromString(selectorString)
let complete : Any = onComplete("complete")
self.perform(selector, with: complete)
}
functionCaller("aFunction:onComplete:", paramString: "anotherParameter", onComplete: { (_ myString ) -> Void in
let string = myString as! String
print(string)
})
我对它进行了测试,并在swift3中运行
让js=“try{(callBackKey)('(value)”);delete window.(callBackKey);}catch(e){}
(jsContext作为?TYWKWebView)?.evaluateJavaScript(js,completionHandler:nil)
}
let handlerDict:[String:Any]=[TYJSBridge.COMPLETION\u HANDLER\u KEY:completionHandler]
让u=jsInterfaceObject.perform(sel,with:parameters,with:handlerDict)
}当我在我的条件下尝试此操作时(有两个函数,一个是中间件,一个是objc,还有一个调用者),我得到了EXC\u BAD\u访问权限。您的示例和我的示例之间的区别是我有2个函数和1个函数调用方。(顺便说一句,当我按照您的建议将其更改为Any时,只是错误更改为EXC_BAD_ACCESS),在您的示例中,您决定在functionCaller
onComplete(“complete”)
中将什么作为字符串放入闭包参数中,但我希望它通过使用选择器调用的另一个函数传递(在我的示例中,它被称为函数)