这个IBAction带来了一个带有两个文本框的UIAlertController。一个名字的盒子和一个年龄的盒子。我正在尝试这样做,以便用户不必输入他们的年龄,如果他们不想。现在,如果他们没有进入他们的年龄,应用程序就会被person.age = Int16(points!)!
行崩溃说“线程1:致命错误:在解开一个Optional值时意外发现nil”。我试图使用if else语句来阻止它。我错过了什么?
@IBAction func addRowBtn(_ sender: Any) {
let alert = UIAlertController(title: "Add Person", message: nil, preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Task"
}
alert.addTextField { (textField) in
textField.placeholder = "Points"
textField.keyboardType = .numberPad
}
let action = UIAlertAction(title: "post", style: .default) { (_) in
let name = alert.textFields?.first!.text!
let age = alert.textFields?.last!.text!
if name != nil && age != nil {
let person = Person(context: PersistenceServce.context)
person.name = name
person.age = Int16(age!)!
PersistenceServce.saveContext()
self.people.append(person)
self.table.reloadData()
}
if name != nil && age == nil {
let person = Person(context: PersistenceServce.context)
person.name = name
person.age = 0
PersistenceServce.saveContext()
self.people.append(person)
self.table.reloadData()
}
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
答案 0 :(得分:1)
为了避免解开问题,我建议你这样做:
let action = UIAlertAction(title: "post", style: .default) { (_) in
if let ageString = alert.textFields?.last?.text,
let age = Int16(ageString),
let name = alert.textFields?.first?.text {
let person = Person(context: PersistenceServce.context)
person.name = name
person.age = age
PersistenceServce.saveContext()
self.people.append(person)
self.table.reloadData()
} else if let name = alert.textFields?.first?.text {
let person = Person(context: PersistenceServce.context)
person.name = name
person.age = 0
PersistenceServce.saveContext()
self.people.append(person)
self.table.reloadData()
}
}