Update 1: I have changed some of the code in line with what is presented in the next of the Stanford lectures. I also removed the code I added to AppDelegate because I saw there was a name clash there. The error message remains the same.
I am developing an iOS app of my own while following the Stanford Developing iOS 10 Apps with Swift course. I am struggling with getting my database set up however. I have created a minimal example of the issue I am running into. I am trying to create an Extension for an Entity in my database. I am trying my best to follow the example code in the slides from Lecture 10 of the course, because I just specifically need to get this simple app finished. However there are certain obstacles I ran into that led me to make changes:
1) Although I am directed to set the Module to Current Product Module this does not work (xcode cannot find the files that way) so I am setting it to Global Namespace instead
2) The professor creates Tweet entities in his example using:
if let tweet = Tweet(context: context) {
tweet.text = “some string”
// more code
}
However this does not work, xcode complains that Tweet is not an optional (“initializer for conditional binding must have optional type”).
Those aside, in my example I am trying to do something very simple. I am just trying to set up a CoreData database and add an entry to it. The error message I get when I do so is: “An NSManagedObject of class 'database_test.Subject' must have a valid NSEntityDescription.”
Here is the step-by-step of the code I generated to test this issue:
1) created a new Swift project using CoreData
2) Here is my AppDelegate.swift
//
// AppDelegate.swift
// database_test
//
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: "database_test")
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)")
}
}
}
}
3) Created Subject entity with one attribute (uniqueID). This is in the Global namespace (see linked). I do the Codegen for a Category/Extension. I then create Subject.swift and fix it to import CoreData and add some code for adding unique subjects:
//
// Subject.swift
// database_test
//
import UIKit
import CoreData
class Subject: NSManagedObject {
class func addSubject(adding newSubject: String, in context: NSManagedObjectContext) throws {
let request: NSFetchRequest<Subject> = Subject.fetchRequest()
request.predicate = NSPredicate(format: "uniqueID = %@", newSubject)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
assert(matches.count==1, "Subject.addSubject - matches.count > 1")
}
} catch {
throw(error)
}
let subject = Subject(context: context)
subject.uniqueID = newSubject
}
}
4) Here are the codegen files from DerivedData:
// Subject+CoreDataProperties.swift
//
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
extension Subject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Subject> {
return NSFetchRequest<Subject>(entityName: "Subject");
}
@NSManaged public var uniqueID: String?
}
// database_test+CoreDataModel.swift
//
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
5) I then test adding something to the database
//
// ViewController.swift
// database_test
//
// Created by Alex B on 2017-07-10.
// Copyright © 2017 Alex B. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
//let context = AppDelegate.viewContext
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
testAdding(subjectID: "John")
}
func testAdding(subjectID: String) {
container?.performBackgroundTask { context in
try?Subject.addSubject(adding: subjectID, in: context)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Running this in the simulator I get terminating with uncaught exception of type NSException which traces back to Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'database_test.Subject' must have a valid NSEntityDescription.'