SwiftUI 和@FetchRequest 中的动态 NSSortDescriptors

SwiftUI and dynamic NSSortDescriptors in @FetchRequest

我有一个包含标题和日期的项目列表。用户可以设置排序依据(标题或日期)。

但是我不知道如何动态更改 NSSortDescriptor。

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Test.title, ascending: true)], animation: .default) private var items: FetchedResults<Test>

    @State private var sortType: Int = 0
    @State private var sortDescriptor: NSSortDescriptor = NSSortDescriptor(keyPath: \Test.title, ascending: true)

    var body: some View {
        Picker(selection: $sortType, label: Text("Sort")) {
            Text("Title").tag(0)
            Text("Date").tag(1)
        }
        .pickerStyle(SegmentedPickerStyle())
        .onChange(of: sortType) { value in
            sortType = value

            if sortType == 0 {
                sortDescriptor = NSSortDescriptor(keyPath: \Test.title, ascending: true)
            } else {
                sortDescriptor = NSSortDescriptor(keyPath: \Test.date, ascending: true)
            }
        }

        List {
            ForEach(items) { item in
                let dateString = itemFormatter.string(from: item.date!)
                HStack {
                    Text(item.title!)
                    Spacer()
                    Text(dateString)
                }
            }
        }

        .onAppear(perform: {
            if items.isEmpty {
                let newEntry1 = Test(context: self.viewContext)
                newEntry1.title = "Apple"
                newEntry1.date = Date(timeIntervalSince1970: 197200800)

                let newEntry2 = Test(context: self.viewContext)
                newEntry2.title = "Microsoft"
                newEntry2.date = Date(timeIntervalSince1970: 168429600)

                let newEntry3 = Test(context: self.viewContext)
                newEntry3.title = "Google"
                newEntry3.date = Date(timeIntervalSince1970: 904903200)

                let newEntry4 = Test(context: self.viewContext)
                newEntry4.title = "Amazon"
                newEntry4.date = Date(timeIntervalSince1970: 773402400)

                if self.viewContext.hasChanges {
                    try? self.viewContext.save()
                }
            }
        })
    }
}

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .none
    return formatter
}()

当我改变

@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Test.title, ascending: true)], animation: .default) private var items: FetchedResults<Test>

@FetchRequest(sortDescriptors: [sortDescriptor], animation: .default) private var items: FetchedResults<Test>

出现错误“无法在 属性 初始化器中使用实例成员 'sortDescriptor';属性 初始化器 运行 在 'self' 可用之前”。

我还尝试将 NSSortDescriptor 存储在 UserDefault 中并创建一个 init 来创建它自己的 FetchRequest.. 仍然没有动态排序...

有人指点一下在哪里可以解决这个问题吗?

在此处找到整个项目:https://github.com/l1ghthouse/FRDSD

已解决!感谢 Asperi 指出此 QA:

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @AppStorage("firstLaunch") var firstLaunch: Bool = true
    @State var sortDescriptor: NSSortDescriptor = NSSortDescriptor(keyPath: \Test.title, ascending: true)
    @State private var sortType: Int = 0

    var body: some View {
        Picker(selection: $sortType, label: Text("Sort")) {
            Text("Title").tag(0)
            Text("Date").tag(1)
        }
        .pickerStyle(SegmentedPickerStyle())
        .onChange(of: sortType) { value in
            sortType = value

            if sortType == 0 {
                sortDescriptor = NSSortDescriptor(keyPath: \Test.title, ascending: true)
            } else {
                sortDescriptor = NSSortDescriptor(keyPath: \Test.date, ascending: true)
            }
        }

        ListView(sortDescripter: sortDescriptor)

        .onAppear(perform: {
            if firstLaunch == true {
                let newEntry1 = Test(context: self.viewContext)
                newEntry1.title = "Apple"
                newEntry1.date = Date(timeIntervalSince1970: 197200800)

                let newEntry2 = Test(context: self.viewContext)
                newEntry2.title = "Microsoft"
                newEntry2.date = Date(timeIntervalSince1970: 168429600)

                let newEntry3 = Test(context: self.viewContext)
                newEntry3.title = "Google"
                newEntry3.date = Date(timeIntervalSince1970: 904903200)

                let newEntry4 = Test(context: self.viewContext)
                newEntry4.title = "Amazon"
                newEntry4.date = Date(timeIntervalSince1970: 773402400)

                if self.viewContext.hasChanges {
                    try? self.viewContext.save()
                }

                firstLaunch = false
            }
        })
    }
}

struct ListView: View {
    @FetchRequest var items: FetchedResults<Test>
    @Environment(\.managedObjectContext) var viewContext

    init(sortDescripter: NSSortDescriptor) {
        let request: NSFetchRequest<Test> = Test.fetchRequest()
        request.sortDescriptors = [sortDescripter]
        _items = FetchRequest<Test>(fetchRequest: request)
    }

    var body: some View {
        List {
            ForEach(items) { item in
                let dateString = itemFormatter.string(from: item.date!)
                HStack {
                    Text(item.title!)
                    Spacer()
                    Text(dateString)
                }
            }
        }
    }
}

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .none
    return formatter
}()