ios - 如何使用模型类初始化 Core Data ManagedObjectContext?

标签 ios swift core-data

我正在关注核心数据堆栈的 Apple 文档,特别是 Initializing the Core Data Stack .

这是我的代码:

import Foundation
import CoreData
class Cmodel: NSObject {
var managedObjectContext: NSManagedObjectContext

init(completionClosure: @escaping () -> ()) {
    //This resource is the same name as your xcdatamodeld contained in your project
    guard let modelURL = Bundle.main.url(forResource: "MySampleListView", withExtension:"momd") else {
        fatalError("Error loading model from bundle")
    }
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
        fatalError("Error initializing mom from: \(modelURL)")
    }

    let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

    managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = psc

    let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
    queue.async {
        guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
            fatalError("Unable to resolve document directory")
        }
        let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            //The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
            DispatchQueue.main.sync(execute: completionClosure)
        } catch {
            fatalError("Error migrating store: \(error)")
        }
    }
}
}

我正在尝试从 Appdelegate 类访问该对象:-

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

        DispatchQueue.main.async {
            self.context = self.managedOBJ?.managedObjectContext
        }
    })

    saveValues()
    // Override point for customization after application launch.
    return true
}. 

这就是我的使用方式。

//Save Local DB
extension AppDelegate {

  func saveValues()  {
    let testQuestionModel : Kishor = NSEntityDescription.insertNewObject(forEntityName: "Kishor", into: AppDelegate.getContext()) as! Kishor

    testQuestionModel.name = "Kishor Da Pahalwani"

    self.saveContext()
  }
}

我遇到 fatal error 。

我不知道原因,但也许 saveValues() 在 Core Data 托管上下文对象初始化之前被调用?或者我可能以错误的方式初始化?

我正在尝试遵循 Apple 文档,但我不知道我错过了什么。

最佳答案

saveValuescompletionClosure 外部调用。这是您收到 fatal error 的方式。核心数据堆栈尚未准备好。

您能解释一下您想要实现什么目标吗?

关于ios - 如何使用模型类初始化 Core Data ManagedObjectContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45919268/

相关文章:

ios - iOS 模拟器中存在头文件,但 iOS 设备上不存在...?

ios - Braintree 点对点 iOS

iPhone Core Data 获取日期操作

ios - 如何使用Unity在iPhone上加载XML文件?

swift - 如何使用 UI 单元测试获取嵌入式框架的 Xcode 8 代码覆盖率

ios - 如何在 iOS swift 中添加 LinkedIn OAuth 2.0 身份验证?

ios - CocoaPods 生成的项目的 .travis.yml 中无法识别语言

iOS 共享扩展 - 如何访问核心数据

ios - 如何将 UITextField 中的值与 CoreData 值进行比较

ios - UICollectionview 数据加载问题