如何在 AppDelegate 中包含 NSPersistentContainer

Posted

技术标签:

【中文标题】如何在 AppDelegate 中包含 NSPersistentContainer【英文标题】:How to include NSPersistentContainer in AppDelegate 【发布时间】:2016-12-20 13:01:22 【问题描述】:

我收到一个错误:

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
()

【问题讨论】:

尝试this 并告知是否不起作用。 viewContext 不是NSPersistentStoreCoordinator 上的方法,而是NSPersistentContainer 上的方法。 > 在 AppDelegate.swift 文件中,NSPersistentStoreCoordinator 被定义为默认值。 - 发布这部分代码。 【参考方案1】:

你应该先导入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

【讨论】:

我已经导入了 CoreData 框架。现在也尝试编写您的代码。它说“使用未声明的类型'NSPersitentContainer'。即使在AppDelegate.swift文件中,默认的类方法'NSPersistentStoreCoordinator'也会显示为'NSPersistenContainer'。 请在您的 AppDelegate 中写上 persistentContainer 类方法... 我做到了。它报告'使用未声明的类型 NSPersistentContainer' 但是在你的问题中你声明了 persistentStoreCoordinator 并且在 viewDidLoad() 你使用了 persistentContainer。 谢谢@pragnesh Vitthani【参考方案2】:

将上面的代码写入 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
()

【讨论】:

【参考方案3】:

如果您使用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 中添加以下内容,因为我们大多数人将在SceneDelegate 类中创建context 对象

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

【讨论】:

以上是关于如何在 AppDelegate 中包含 NSPersistentContainer的主要内容,如果未能解决你的问题,请参考以下文章

如何更改应用程序委托类?

在 appDelegate 中使用 Navigation 编程 TabBarController

如何在 GNUMakefile 中包含 libxml2 库

如何在 ConfigurationSection 中包含简单集合

如何在 .tsx 打字稿中包含 .css 文件?

如何在 SwiftUI 中包含和调用 BSImagePicker