Reputation: 131
I am working on the last leg of my app and this seems to be the last portion I'm having issue with. Fingers crossed for that, anyway.
I have CoreData all set up and ready to be displayed in a table (hopefully, I can't really view it in a table yet to verify).
The issue I'm having right now is that when the views that implement CoreData load, there is a fatal error that occurs when it initiates my NSManagedObjectContext. Please note that I use two separate ViewControllers to get data in addition to the TableViewController, therefore I have declared a total of 3 NSManagedContextObjects in my app - which I'm not sure if that's the issue or not. The line that is causing it is in my viewDidLoad function. See the code below.
override func viewDidLoad() {
super.viewDidLoad()
managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
}
I'm not entirely sure how to tackle this, for I was following a tutorial for the whole process.
EDIT: I am going to add all the code that is affected by CoreData so maybe it'll help the problem be solved.
Here is a screenshot of my core data model
AppDelegate
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
//self.saveContext()
}
// MARK: - Core Data Stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "RSDB_1_0_COREDATA")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
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 {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
First View Controller
let newInfo = GeneralInfo(context:managedObjectContext1)
newInfo.courseNumber = studCourse
newInfo.scenarioNumber = studScen
do {
try self.managedObjectContext1.save()
}catch {
print("Could not save data \(error.localizedDescription)")
}
performSegue(withIdentifier: "segue3", sender: self)
Different View Controller
let newEvaluation = GeneralEvaluation(context:managedObjectContext)
newEvaluation.idScore = String(ID)
newEvaluation.washScore = String(WASH)
newEvaluation.totalScore = String(total)
do {
try self.managedObjectContext.save()
}catch {
print("Could not save data \(error.localizedDescription)")
}
performSegue(withIdentifier: "segue4", sender: self)
TableViewController
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TheTableViewCell
let info = courseInfo[indexPath.row]
let score = scores[indexPath.row]
cell.CLASS.text = info.courseNumber
cell.SCENARIO.text = info.scenarioNumber
cell.WASH.text = score.washScore
cell.ID.text = score.idScore
cell.TOTAL.text = score.totalScore
Upvotes: 1
Views: 374
Reputation: 7646
Looks like you're throwing an error in your lazy var persistentContainer. That's good. That means you can rule out the view controllers as the cause. Can we see a screenshot of the files section of Xcode (command-1)?
Upvotes: 0
Reputation: 7646
It would be helpful to see the text of the error message, and the stack trace.
You could start by breaking down that chain of calls, to narrow down where you're crashing.
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
let container = appDelegate.persistentContainer
managedObjectContext = container.viewContext
Is your stack (persistent container/persistent store coordinator/managed object model/managed object context instantiated before you load the view controller? It appears not. Since you crash so early, I'm going out on a limb and guessing that you have a spelling error or name mismatch somewhere (a filename that doesn't match what's in your defining code). Or perhaps your MOM is not included as a resource in your bundle?
Upvotes: 1