gpt4 book ai didi

ios - 如何在 AppDelegate 中包含 NSPersistentContainer

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:34 25 4
gpt4 key购买 nike

我收到一个错误:

AppDelegate has no member 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
}()

最佳答案

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

关于ios - 如何在 AppDelegate 中包含 NSPersistentContainer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com