我将CoreData添加到现有项目中,但我无法将NSPersistentContainer
添加到Initialize中。这是我在App Delegate中的代码:
var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "TimeConverter")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
只有当我尝试保存managedObjectContext时,应用程序才会崩溃。错误(在App Delegate中)是:
Thread 1: signal SIGABRT
为什么没有初始化?
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)")
}
}
}
此外,这里是在viewcontroller中调用的地方
func save(event: String,fromCourse:String,toCourse:String,fromTime:String,convertedTime: String)
{
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate
else
{
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "ConversionHistory",
in: managedContext)!
let conversion = NSManagedObject(entity: entity,
insertInto: managedContext);
conversion.setValue(event, forKeyPath: "event")
conversion.setValue(fromCourse, forKeyPath: "fromCourse")
conversion.setValue(toCourse, forKeyPath: "toCourse")
conversion.setValue(fromTime, forKeyPath: "fromTime")
conversion.setValue(convertedTime, forKeyPath: "toTime")
do
{
try managedContext.save()
// people.append(person)
} catch let error as NSError
{
print("Could not save. \(error), \(error.userInfo)")
}
}