Я новичок в разработке Swift и пытаюсь создать базовое приложение, в котором данные вводятся в одном контроллере представления и отображаются в виде таблицы в другом. Это мой код для добавления контроллера представления данных:
Я получаю ошибку:
Поток 1: ошибка EXC_BAD_ACCESS (code = 2, address = 0x7ffee4ffdee8) в моей строке для строки, в которой я определяю константу «context», т.е. let constant = (UIAppli ...
Может кто-нибудь помочь мне понять, почему это так? Большое вам спасибо!
import UIKit
import CoreData
class AddCardViewController: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBOutlet weak var nameTF: UITextField!
@IBOutlet weak var cardNumberTF: UITextField!
@IBOutlet weak var securityCodeTF: UITextField!
@IBOutlet weak var expiryDateTF: UITextField!
let prevVC = CardListViewController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addButtonPressed(_ sender: Any) {
let name = nameTF.text
let number = cardNumberTF.text
let key = securityCodeTF.text
let date = expiryDateTF.text
if (name?.isEmpty)! {
let alert = UIAlertController(
title: "Error",
message: "Please enter your full name",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(
title: "OK",
style: UIAlertActionStyle.default,
handler: nil))
present(alert, animated: true, completion: nil)
} else if (number?.isEmpty)! {
let alert = UIAlertController(
title: "Error",
message: "Please correctly enter your credit card number",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(
title: "OK",
style: UIAlertActionStyle.default,
handler: nil))
present(alert, animated: true, completion: nil)
} else if (key?.isEmpty)! {
let alert = UIAlertController(
title: "Error",
message: "Please correctly enter your security key",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(
title: "OK",
style: UIAlertActionStyle.default,
handler: nil))
present(alert, animated: true, completion: nil)
} else if (date?.isEmpty)! {
let alert = UIAlertController(
title: "Error",
message: "Please enter your card's expiry date",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(
title: "OK",
style: UIAlertActionStyle.default,
handler: nil))
present(alert, animated: true, completion: nil)
} else {
let newCard = CardsData(context: self.context)
newCard.id = Int32(prevVC.itemArray.count)
newCard.fullname = nameTF.text
newCard.cardnumber = cardNumberTF.text
prevVC.itemArray.append(newCard)
self.saveCard()
}
}
func saveCard() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
performSegue(withIdentifier: "backToDBView", sender: self)
}
func loadCards() {
let request : NSFetchRequest<CardsData> = CardsData.fetchRequest()
do {
prevVC.itemArray = try context.fetch(request)
} catch {
print("Error fetching data from \(error)")
}
}
}
РЕДАКТИРОВАТЬ: Вот мой код в классе AppDelegate:
импорт UIKit
импорт CoreData
@ UIApplicationMain
Класс AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
} * * тысяча двадцать-один