如何为此 SwiftUI CoreData 模型正确插入排序描述符?

How do I correctly insert a sort descriptor for this SwiftUI CoreData model?

我正在尝试实现此处所述的 MVVM 架构:

https://medium.com/better-programming/swiftui-and-coredata-the-mvvm-way-ab9847cbff0f

但是我在这个文件中遇到了 运行 次错误,无法确定在何处添加排序描述符:

import Foundation
import CoreData
import Combine
import UIKit

class ItemsStorage: NSObject, ObservableObject {
    var items = CurrentValueSubject<[Item], Never>([])
    private let itemFetchController: NSFetchedResultsController<Item>
    
    //SINGLETON INSTANCE
    static let shared: ItemsStorage = ItemsStorage()  ///Run time error: Thread 1: "An instance of NSFetchedResultsController requires a fetch request with sort descriptors"
    
    private override init() {
        
        /// This line doesn't solve the issue
        let sort = NSSortDescriptor(key: "name_", ascending: true)
        
        itemFetchController = NSFetchedResultsController(
        
        fetchRequest: Item.fetchRequest(),
        managedObjectContext: PersistenceController.shared.container.viewContext,
        sectionNameKeyPath: nil, cacheName: nil
        )
        
        /// This line doesn't solve the issue
        itemFetchController.fetchRequest.sortDescriptors = [sort]
        
        super.init()
        
        itemFetchController.delegate = self
        
        do {
            try itemFetchController.performFetch()
            items.value = itemFetchController.fetchedObjects ?? []
        } catch {
            NSLog("Error: could not fetch objects")
        }
    }
    
    func add(){
        
    }
    
    func update(withID id: UUID) {
        
    }
    
    func delete(id: UUID) {
        
    }
}

extension ItemsStorage: NSFetchedResultsControllerDelegate  {
    public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        guard let items = controller.fetchedObjects as? [Item] else { return }
        NSLog("Context has changed, reloading items ...")
        self.items.value = items
    }
}

在初始化抓取结果控制器之前,您需要为抓取请求设置排序描述符:

    let sort = NSSortDescriptor(key: "name_", ascending: true)
    let itemFetchRequest = Item.fetchRequest()
    itemFetchRequest.sortDescriptors = [sort]
    
    itemFetchController = NSFetchedResultsController(
    
    fetchRequest: itemFetchRequest,
    managedObjectContext: PersistenceController.shared.container.viewContext,
    sectionNameKeyPath: nil, cacheName: nil
    )