我有一个这样声明的函数:
func rspGetCategories(_ response: (Int, [String:Any])) {
我试着这样称呼它:
self.perform(act, with: (tag, outjson))
其中:
act = Selector(("rspGetCategories:"))
tag = 1
outjson = ["status":"ServerError"]
我刚收到一个"无法识别的选择器发送…"。我缺少什么?
完整错误消息:
2018-07-18 11:20:15.852755+0200 Appname[8071:4529543] -[Appname.ViewController rspGetCategories:]: unrecognized selector sent to instance 0x10380be00
2018-07-18 11:20:15.853361+0200 Appname[8071:4529543] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Appname.ViewController rspGetCategories:]: unrecognized selector sent to instance 0x10380be00'
*** First throw call stack:
(0x18418ed8c 0x1833485ec 0x18419c098 0x18e27edb0 0x1841945c8 0x18407a41c 0x1020f5dfc 0x1020ebc3c 0x102f811dc 0x102f8119c 0x102f85d2c 0x184137070 0x184134bc8 0x184054da8 0x186039020 0x18e071758 0x1020fec34 0x183ae5fc0)
libc++abi.dylib: terminating with uncaught exception of type NSException
由于selector
方法应该由Objective-C
表示,因此对于@objc
,我们不能将元组作为方法的参数传递,否则编译器将抛出此错误,
方法不能标记为@objc,因为参数的类型不能在Objective-C 中表示
一个可能的解决方案如下,
@objc func rspGetCategories(_ response: [String: Any]) {
print("Tag: (response["tag"] as! Int) Status:(response["status"] as! String)")
}
并构建如下响应,
let selector = #selector(rspGetCategories(_:))
let tag = 1
let response: [String: Any] = ["tag": tag,
"status": "ServerError"]
self.perform(selector, with: response)
另一个解决方案是传递两个参数而不是元组。如下所示,
@objc func rspGetCategories(_ tag: NSNumber, response: [String: Any]) {
print("(tag.intValue) (response)")
}
let selector = #selector(rspGetCategories(_:response:))
let tag = 1
let response = ["status": "ServerError"]
self.perform(selector, with: tag, with: response)
请记住,selector
方法argument
type
需要是reference type
。
将元组拆分为两个参数,如
@objc func rspGetCategories(_ response: Int, dict: [String: Any]) {
并更改选择器
let act = #selector(Test.rspGetCategories(_:dict:))
Test
是我的类名,用你的类名代替