如何在AppDelegate中包含NSPersistentContainer

问题描述 投票:6回答:3

我收到错误:

AppDelegate没有成员persistentContainer

import UIKit
import CoreData

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext // Error: value of type 'AppDelegate' has no member 'persistentContainer'
    }

}

在AppDelegate.swift文件中,NSPersistentStoreCoordinator被定义为默认值。

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    }
    catch {
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }
    return coordinator
}()
ios swift core-data swift3
3个回答
17
投票

您首先应该import CoreData框架,然后编写此代码在AppDelegate.swift

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "Your Model File Name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()

然后您应该写这个:

 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

0
投票

将上面的代码写到AppDelegate中,在窗口变量下你必须用方法写出这段代码AppDelegate类:UIResponder,UIApplicationDelegate {

var window: UIWindow?
lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name:"Model.anthing")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()

0
投票

如果使用SwiftUI框架,请在AppDelegate.swift中编写以下内容:>

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "Your Model File Name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()

并且,在SceneDelegate.swift中添加以下内容,因为我们大多数人将在context类中创建SceneDelegate对象

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
© www.soinside.com 2019 - 2024. All rights reserved.