gpt4 book ai didi

ios - 在 AppDelegate 中为其他 Viewcontroller 初始化 managedContect

转载 作者:行者123 更新时间:2023-11-28 06:07:44 26 4
gpt4 key购买 nike

我想初始化 managedObject,但我总是得到这个错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我想使用 Core Data/managedObject 的 ViewController 不是我启动的 ViewController,而是我通过启动 ViewController 访问的另一个 (PortfolioVC)。

这是我的代码:

import Foundation
import CoreData

class DatabaseController {
private let modelName: String

init(modelName: String) {
self.modelName = modelName
}

lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()

private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()

func saveContext () {
guard managedContext.hasChanges else { return }

do {
try managedContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
}

这是我的 AppDelegate:

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
lazy var coreDataStack = DatabaseController(modelName: "Portfolio")

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

guard let navController = window?.rootViewController as? UINavigationController,
let viewController = navController.topViewController as? PortfolioVC else {
return true
}
viewController.managedContext = coreDataStack.managedContext
return true
}

func applicationWillResignActive(_ application: UIApplication) {

}

func applicationDidEnterBackground(_ application: UIApplication) {

coreDataStack.saveContext()
}

func applicationWillEnterForeground(_ application: UIApplication) {

}

func applicationDidBecomeActive(_ application: UIApplication) {

}

func applicationWillTerminate(_ application: UIApplication) {

coreDataStack.saveContext()
}


}

这是 PortfolioVC 中的代码:

导入 UIKit导入核心数据

class PortfolioVC: UIViewController {


var managedContext: NSManagedObjectContext!
var namePortfolio: NamePortfolio?

override func viewDidLoad() {
super.viewDidLoad()
tableViewPortfolio.dataSource = self

let standardPortfolio = "Watchlist"
let fetchRequest: NSFetchRequest<NamePortfolio> = NamePortfolio.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(NamePortfolio.name), standardPortfolio)

do {
let results = try managedContext.fetch(fetchRequest) // here I get the error (managedContext = nil)
if results.count > 0 {
// Portfolio already created
namePortfolio = results.first

} else {
// no Portfolio
namePortfolio = NamePortfolio(context: managedContext)
namePortfolio?.name = standardPortfolio
try managedContext.save()
}
} catch let error as NSError {

print("Could not fetch \(error), \(error.userInfo)")
}

}

非常感谢您的帮助!

最佳答案

didFinishLaunchingWithOptions 中的代码运行时,PortfolioVC 尚未添加到导航 Controller 堆栈(甚至实例化),因此守卫失败。有两种方法可以将 managedContext 获取到 PortfolioVC:

a) 在 didFinishLaunchingWithOptions 中将其传递给启动 View Controller ,然后使用 prepareForSegue 从那里将其传递给 PortfolioVC。您需要向启动 VC 添加一个 managedContext 属性,即使您只需要将它传递给 Portfolio VC。

b) 在 PortfolioVC 中,获取对 AppDelegate 的引用,然后从那里获取 managedContext。

    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
managedContext = appDelegate.coreDataStack.managedContext
}

关于哪一个是更好的设计模式,意见不一。

关于ios - 在 AppDelegate 中为其他 Viewcontroller 初始化 managedContect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47749286/

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