我正在尝试实现如下所述的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
}
}
最佳答案
在初始化提取的结果 Controller 之前,您需要为fetchRequest设置排序描述符:
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
)
关于swift - 如何为该SwiftUI核心数据模型正确插入排序描述符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/66081123/