类型的价值' AppDelegate'没有会员' manageObjectContext'

时间:2017-02-26 11:48:12

标签: ios swift core-data

我想在TableView中为来自Swift 3的iOS应用程序打印来自CoreData的数据。

在ListTableViewController文件中我有这段代码:

    override func viewDidAppear(_ animated: Bool) {
    let appDel: AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObjectContext = appDel.persistentContainer.viewContext
    let contxt :NSManagedObjectContext = appDel.managedObjectContext!

    let freq = NSFetchRequest<NSFetchRequestResult>(entityName:"Location")


    tableView.reloadData()
}

在let上下文行中,我发现了一个错误:&#34;类型值&#39; AppDelegate&#39;没有会员&#39; manageObjectContext&#39;&#34;

您对我的问题有所了解吗?

感谢&#39; S

2 个答案:

答案 0 :(得分:3)

错误表示您未在Appdeleget中将任何值分配给变量名称managedObjectContext。首先,您必须定义一个变量,然后将ManagedObjectContext对象分配给它。但您可以通过以下代码获取ManagedObjectContext对象引用。

let managedObjectContext = appDel.persistentContainer.viewContext as! NSManagedObjectContext
let contxt = managedObjectContext

答案 1 :(得分:-1)

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "CoreDataCRUD")
    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 {
            // 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)")
        }
    }
}