我目前有一个函数可以从数据库中收集时间并将其返回给其他函数使用。它需要一个参数,该参数存储在应用程序的另一部分中,以便从数据库中收集值。
当我想在IBAction函数中调用此函数时,我的问题出现了。
这是我的函数代码:
func getDBValue(place: GMSPlace) -> Int {
var expectedValue = 0
databaseRef.child("values").child(place.placeID).observe(.value, with: { (snapshot) in
let currentValue = snapshot.value as? [Int]
if currentValue == nil {
self.noValue()
expectedValue = 0
} else {
let sumValue = currentValue?.reduce(0, +)
let avgValue = sumValue! / (currentValue?.count)!
print("The current value is \(String(describing: avgValue))")
expectedValue = avgValue
self.valueLabel.text = String(describing: avgValue)
}
})
print("This is the expected WT: \(expectedWaitTime)")
return expectedValue
}
这是我的IBAction函数的代码,它存在多个参数的问题:
@IBAction func addValuePressed(_ sender: Any, place: GMSPlace) {
print("This is the place ID: \(place.placeID)")
var expectedValue = getDBValue(place: place)
expectedValue = expectedValue + 1
print("The expectedValue is now: \(expectedValue)")
self.valueLabel.text = String(describing: expectedValue)
}
这给了我一个libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
错误。经过一些测试后,似乎错误是由我的IBAction函数中添加的参数place: GMSPlace
引起的。关于如何解决这个问题的任何想法?
答案 0 :(得分:5)
IBAction
方法不能有任意签名。您无法在此处添加额外参数。按钮无法向您发送此信息(按钮如何知道place
是什么?)通常,只有一个UI元素指向此操作(因此您知道按下了哪个按钮) ,或使用发件人上的tag
来识别它。每个视图都有一个tag
属性,它只是一个整数。您可以在Interface Builder或代码中进行设置,然后您可以读取它以识别发件人。
首先阅读文档中的Target Action,了解其在各种平台上的工作原理。通常,IBAction
的签名必须是:
@IBAction func action(_ sender: Any)
但是,在iOS上,它也可能是:
@IBAction func action(_ sender: Any, forEvent: UIEvent)
正如泰勒M在下面指出的那样,你也可以使用这个签名(虽然我不能记得,如果这在iOS之外有效;我只是亲自在那里使用它。)
@IBAction func action()
但就是这样。没有其他允许的签名。