我正在尝试从 subview Controller 回调到其父 View 。传回的值已成功打印,但随后我得到一个 EXC_BAD_INSTRUCTION
。
在父 View Controller 中,我像这样构建子 Controller :
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewControllerWithIdentifier("dataEntryView") as? DataEntryViewController {
dataEntryVC = vc
vc.callback = calculateHeartRate
self.presentViewController(dataEntryVC!, animated: true, completion: nil)
}
我像这样从子 Controller 回调:
@IBAction func done(sender : AnyObject) {
dismissModalViewControllerAnimated(true)
if let cb = callback {
cb(beatCount)
}
}
父 Controller 中的这个函数:
func calculateHeartRate(beats : Int?) {
println("Beats = \(beats)")
if beats {
let heartrate = 60/secondsCount * beats!
println("Heart rate \(heartrate)")
}
}
println 正确输出到控制台,然后我在“if beats {”行出现异常。
像这样进行回调有什么内在的错误吗?
最佳答案
我终于明白了。它与我使用的 Optionals 语法或使用闭包与函数无关。
根本原因是@IBOutlets 是弱引用。
当我将我的“完成”方法更改为立即缓存在变量中输入的值时,一切都开始工作:)
初始化
class DataEntryViewController: UIViewController {
@IBOutlet var beatsText : UITextField
var callback : ((Int?) -> Void)?
var beatCount : Int?
@IBAction func done(sender : AnyObject) {
beatCount = beatsText.text.toInt()
dismissModalViewControllerAnimated(true)
if let cb = callback {
cb(beatCount)
}
}
用法
let dataEntryViewController = DataEntryViewController()
dataEntryViewController.callback = {
(beatCount) in
print(beatCount)
}
关于cocoa - 如何在 Swift 中执行 View Controller 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486959/