我在didSelectRow
功能
在某些情况下,选择器视图可能为零,因此didSelectRow
内的所有指令都会读取无值,并且应用程序崩溃。
我多次使用不同的解决方案来防止此次崩溃,但它无法正常工作:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (self.MEDARRAY[row].value(forKey: "medNumDay") as? NSInteger) != nil {
let NumDay = self.MEDARRAY[row].value(forKey: "medNumDay") as? NSInteger
let NumMed = self.MEDARRAY[row].value(forKey: "medNum") as? NSInteger
Counter = (self.MEDARRAY[row].value(forKey: "takenCounter") as? NSInteger)!
theTimeSet = (self.MEDARRAY[row].value(forKey: "nextTime")as? Date)!
numberforday = (24 / NumDay!)
thegetting.timeStyle = DateFormatter.Style.short
TotalDose.text = String(NumDay! * NumMed!)
RemainDose.text = String(Int(TotalDose.text!)! - Counter!)
NextTimes.text = thegetting.string(from: theTimeSet!)
}
else{
TotalDose.text = "No"
RemainDose.text = "No"
NextTimes.text = "No"
}
}
另一次尝试
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (MEDARRAY.count < 1) {
let NumDay = self.MEDARRAY[row].value(forKey: "medNumDay") as? NSInteger
let NumMed = self.MEDARRAY[row].value(forKey: "medNum") as? NSInteger
Counter = (self.MEDARRAY[row].value(forKey: "takenCounter") as? NSInteger)!
theTimeSet = (self.MEDARRAY[row].value(forKey: "nextTime")as? Date)!
numberforday = (24 / NumDay!)
thegetting.timeStyle = DateFormatter.Style.short
TotalDose.text = String(NumDay! * NumMed!)
RemainDose.text = String(Int(TotalDose.text!)! - Counter!)
NextTimes.text = thegetting.string(from: theTimeSet!)
}
else{
TotalDose.text = "No"
RemainDose.text = "No"
NextTimes.text = "No"
}
}
问题是它仍然试图通过此错误获取以下代码的值:索引超出范围
let NumDay = self.MEDARRAY[row].value(forKey: "medNumDay") as? NSInteger
let NumMed = self.MEDARRAY[row].value(forKey: "medNum") as? NSInteger
Counter = (self.MEDARRAY[row].value(forKey: "takenCounter") as? NSInteger)!
theTimeSet = (self.MEDARRAY[row].value(forKey: "nextTime")as? Date)!
答案 0 :(得分:0)
如果您要识别的项目是选项,但您需要它们具有非零值来执行该函数,请在函数的头部放置一个保护语句,用于测试每个值是否可用:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard row < MEDARRAY.count,
MEDARRAY.count < 1,
let NumDay : NSInteger = self.MEDARRAY[row].value(forKey: "medNumDay") as NSInteger,
let NumMed = self.MEDARRAY[row].value(forKey: "medNum") as NSInteger,
let Counter = (self.MEDARRAY[row].value(forKey: "takenCounter") as NSInteger
let theTimeSet = (self.MEDARRAY[row].value(forKey: "nextTime") as Date else { print("Could not obtain all required values") ; return }
// ... function continues here...
请注意,您可以使用逗号链接guard语句,并且这些常量不是选项:如果非nil值可用,则它们将初始化为非可选,否则将触发保护异常。 (另请注意对阵列测试和行输入的更正。)
这样,如果您无法将这些常量初始化为非零值,则该函数将退出,这将阻止应用程序崩溃。当然,这并没有解决为什么值为零,但至少会继续执行。
希望有所帮助。