0

I am new to Swift development, and trying to create a basic app where data is entered in one view controller, and is displayed in a table view in another. This is my code for the adding data view controller:

I am getting error:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee4ffdee8) error on my line for line in which I define the "context" constant, i.e. let constant = (UIAppli...

Can anyone help me figure out why this is the case? Thank you so much!

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)")
    }
}

}

EDIT: Here's my code in the AppDelegate class as well:

import UIKit import CoreData

@UIApplicationMain class 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)")
        }
    }
}

}

Devesh Rai
  • 13
  • 4
  • 1
    You should show the exact text of the error message in the question as an [edit]. –  Jul 05 '18 at 16:07
  • Check this answer: https://stackoverflow.com/a/38034677/8346251 – Kevinosaurio Jul 05 '18 at 16:10
  • Thank you for the suggestion, @jdv, made the edit! – Devesh Rai Jul 05 '18 at 16:29
  • @Kevinosaurio, I had that exact piece of code in my app delegate, yet the error persists unfortunately. Thank you for the link though – Devesh Rai Jul 05 '18 at 16:30
  • Exactly when does the error happen? Does it happen when you open the table view for the first time or when you go back to the table view after saving a new entry ? –  Jul 05 '18 at 21:29
  • @Alan the error happens when I try to run my app on the iPhone simulator on Xcode. It loads the simulator, then opens the app. The screen is white for a while, until the simulator shuts down and the error message appears on xCode. – Devesh Rai Jul 06 '18 at 00:38

0 Answers0