我的应用程序中有一个食物日记,可以记录你每天吃的食物,但我正在努力更新我的UITableViewCell中的卡路里标签。只要我按下“保存到食物日记”,我的应用程序就会崩溃,错误如下:
"fatal error: unexpectedly found nil while unwrapping an Optional value"下面是我的PopUpVC (用户可以看到的输入FoodName和Calories的UIViewController)中的代码
protocol AddRowDelegate {
func didAddRow(name : String, calories : String)
}
class PopupVC: UIViewController {
var delegate: AddRowDelegate?
var section: Int?
var caloriesLabel = " "
var tableData: [String] = [""]
var caloriesCell = caloriesForDiary()
@IBOutlet weak var foodTimeLabel: UILabel!
@IBOutlet weak var foodPopup2: UIView!
@IBOutlet weak var foodPopUp: UIView!
@IBOutlet weak var inputFood: UITextField!
@IBOutlet weak var inputCals: UITextField!
@IBAction func saveToDiary(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegate?.didAddRow(name: inputFood.text!, calories: inputCals.text!)
}然后,我将来自食物和卡路里UItextFields的输入传递给我的FoodDiaryVC:
func didAddRow(name: String, calories: String) {
cals.calories.text = calories
print(name)
print(calories)
} 我添加了显示错误和ViewController的图片。我不确定为什么它会发现/返回nil?我基本上只是尝试将我的卡路里标签设置为等于输入(或一天中cals的累积)



发布于 2017-04-22 23:31:21
您的cals或calories对象为nil,这会导致崩溃。您没有在发布的代码中包含此对象,但请确保在访问该对象之前已将其实例化。
发布于 2017-04-23 00:04:52
嗨,我不知道是什么导致了崩溃,但我相信它是可以调试的。按照我的建议执行以下步骤。将didAddRow的方法更改为
func didAddRow(name: String, calories: String) {
if(calories.characters.count != 0 && cal != nil) {
cal.calories.text = calories
}
print(name)
print(calories)
}如果这不能给你合适的结果,那么试着打印卡路里,然后用这种方法调用。检查插座并在此方法中设置断点。
https://stackoverflow.com/questions/43560953
复制相似问题