如何修复无法从 Core Data 获取图像的错误?

How can I fix error that can't fetch image from Core Data?

我想获取从照片库中选取并已保存的图像,但无法获取图像数据。当我调试时,日志显示“已保存图像”,但在 DetailViewController 中显示“无图像获取”。 你有什么想法让我想念什么吗?谢谢

核心数据

数据管理器 : 部分方法与保存和获取备忘录有关。

class DataManager {
    static let shared = DataManager()
    
    private init() {
        
    }
    
    var mainContext: NSManagedObjectContext {
        return persistentContainer.viewContext
    }
    
    var memoList = [Memo]()

    func fetchMemo() {
        let request: NSFetchRequest<Memo> = Memo.fetchRequest()
        
        let sortByDateDesc = NSSortDescriptor(key: "insertDate", ascending: false)
        request.sortDescriptors = [sortByDateDesc]
        
        do {
            memoList = try mainContext.fetch(request)
        } catch {
            print(error)
        }
    }
    
    func addNewMemo(_ memo: String?) {
        
        let newMemo = Memo(context: mainContext)
        newMemo.content = memo
        newMemo.insertDate = Date()

        memoList.insert(newMemo, at: 0)
        
        saveContext()
    }
    

    func deleteMemo(_ memo: Memo?) {
        if let memo = memo {
            mainContext.delete(memo)
            saveContext()
        }
    }

    func saveImage(data: Data) {
        let memo = Memo(context: mainContext)
        memo.image = data
        saveContext()

    }

ComposeViewController:我保存从照片库中挑选的图像的地方

if let memoImage = imageView.image?.pngData() {
                DataManager.shared.saveImage(data: memoImage)
                DataManager.shared.saveContext()

                print("Saved Image") 
            }

            DataManager.shared.addNewMemo(memo)
            NotificationCenter.default.post(name: ComposeViewController.newMemoDidInsert, object: nil)
        }

DetailViewController : 我想要获取图片的地方

DispatchQueue.main.async {
            if let memoImage = self.memo.image {
                self.imageView.image = UIImage(data: memoImage as Data)
            } else {
                print("No image fetch")
            }
        }

您正在保存 2 个备忘录对象,一个没有图像,一个只有图像。我会删除 saveImage 函数并将图像(数据)作为参数添加到 addNewMemo 函数,然后调整调用代码。

func addNewMemo(_ memo: String?, image: Data?) {        
    let newMemo = Memo(context: mainContext)
    newMemo.content = memo
    newMemo.insertDate = Date()
    if let data = image {
        newMemo.image = data
    }

    memoList.insert(newMemo, at: 0)
    
    saveContext()
}

调用代码

let memoImage = imageView.image?.pngData()
DataManager.shared.addNewMemo(memo, image: memoImage)

NotificationCenter.default.post(name: ComposeViewController.newMemoDidInsert, object: nil)