Всем привет. Прохожу курс по coreData, и пытаюсь сохранить данные в массив. В чем собственно смысл : человек вводит текст в текстфилд, после чего нажимает на кнопку. после нажатия этой кнопки должна появляться строчка и сохраняться, но у меня вылетает приложен ие и xcode пишет nil. В чем может быть проблема? Код :
import UIKit
import CoreData
class AddAddres: UIViewController {
var addres: [Addres] = []
@IBOutlet weak var textField: UITextField! // окно для ввода
@IBOutlet weak var tableView: UITableView! // таблица
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
@IBAction func insertRow(_ sender: Any) { // кнопка "Добавить"
insertRow()
guard
let text = textField.text,
!text.isEmpty else { return }
self.saveAddres(addresString: text)
self.tableView.reloadData()
}
func saveAddres(addresString : String) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Addres", in: context)
let addresObject = NSManagedObject(entity: entity!, insertInto: context) as! Addres
addresObject.adressApp = addresString
// addresObject.setValue(addresString, forKey: “addres”)
do {
try context.save()
addres.append(addresObject)
print("Saved! Good Job!")
} catch {
print(error.localizedDescription)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
let result = try context.fetch(Addres.fetchRequest())
addres = result as! [Addres]
} catch {
print(error.localizedDescription)
}
}
private func insertRow() {
guard
let text = textField.text,
!text.isEmpty else { return }
self.saveAddres(addresString: text)
//addres.append(text)
let indexPath = IndexPath(row: addres.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
textField.text = ""
self.view.endEditing(true)
}
}
extension AddAddres: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
insertRow()
textField.resignFirstResponder()
return true
}
}
extension AddAddres: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // кол-во строк
return addres.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let address = addres[indexPath.row]
cell.textLabel?.text = address.value(forKey: "addres") as? String
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if editingStyle == .delete {
//self.tableView.setEditing(true, animated: true)
context.delete(addres[indexPath.row])
(UIApplication.shared.delegate as! AppDelegate).saveContext()
do {
addres = try context.fetch(Addres.fetchRequest())
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
}
}