Core Data Error: Cannot fetch without an NSManagedObjectContext in scope

Core Data Error: Cannot fetch without an NSManagedObjectContext in scope

我在 Swift 中使用 XMPPFramework 库,它使用 Core Data 提供消息历史记录存储。我正在尝试使用以下函数从存储中请求存档消息:

func getChatHistory() {

    guard let context = xmppMessageStorage.mainThreadManagedObjectContext else {return}
    var entityDescription = NSEntityDescription.entity(forEntityName: "XMPPMessageArchiving_Message_CoreDataObject", in: context)
    var request = NSFetchRequest<NSFetchRequestResult>(entityName: "XMPPMessageArchiving_Message_CoreDataObject")
    request.entity = entityDescription
    do {
        var messages = try request.execute()
        print("Archived Messages: \n\(messages)")
    } catch let error {
        print("Error fetching chat history: \(error)")
    }

}

但是,当我执行函数时,我收到以下错误:

Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={message=Cannot fetch without an NSManagedObjectContext in scope}

我不明白为什么会这样,因为我在代码中正确设置了上下文。如果有人能帮助我理解这里出了什么问题,我将不胜感激。

尝试替换

request.entity = entityDescription
do {
  var messages = try request.execute()
  print("Archived Messages: \n\(messages)")
} catch let error {
  print("Error fetching chat history: \(error)")
}

do {
  let messages = try context.fetch(request)
  print("Archived Messages: \n\(messages)")
} catch {
  print("Error fetching chat history:", error)
}