SwiftUI排序描述符 @State

uqxowvwt  于 2023-02-11  发布在  Swift
关注(0)|答案(2)|浏览(138)

我想用一个按钮来改变sortDescriptor。
但如果我将变量"sorting"和"sortOrder"更改为@State变量,则会出现错误。
错误消息为:* 变量"self. fetchRequest"在初始化之前使用 *

@Environment(\.managedObjectContext) private var viewContext
    
@State var sorting: KeyPath = \Log.diveNr
@State var sortOrder: SortOrder = .forward
    
private var fetchRequest: FetchRequest<Log>
private var logs: FetchedResults<Log> {
    fetchRequest.wrappedValue
}
    
init() {
    fetchRequest = FetchRequest(sortDescriptors: [SortDescriptor(sorting, order: sortOrder)])
}

有人能帮我解决这个问题吗?

    • 解决方案:**
@FetchRequest(sortDescriptors: [SortDescriptor(\.diveNr, order: .forward)])
    var logs: FetchedResults<Log>
    
    var body: some View {
        NavigationStack {
            List{
                if logs.count == 0 {
                    Text("no Logs found")
                }
                Button("change order") {
                    logs.sortDescriptors = [SortDescriptor(\.diveNr, order: .reverse)]
                }
                ForEach(logs){log in
                    NavigationLink(destination: DiveLogDetailView(diveNo: 1, diveSite: "Vela Garska")) {
                        DiveLogListObject(log: log)
                    }
                }
                .onDelete(perform: deleteLog)
            }
}
vlf7wbxs

vlf7wbxs1#

由于使用了@State,因此sortingsortOrder都是计算属性。在初始化所有存储属性之前,不能在init中使用计算属性。(否则,计算属性的getter可能会让未完全初始化的self转义。)
因此,请改用底层存储属性:

init() {
    let descriptor = SortDescriptor(
        _sorting.wrappedValue,
        order: _sortOrder.wrappedValue
    )
    fetchRequest = FetchRequest(sortDescriptors: [descriptor])
}
ffscu2ro

ffscu2ro2#

你必须在body中设置它。不幸的是@FetchRequest的设计真的很糟糕。

func updateSort() {
        logs.sortDescriptors = [SortDescriptor(\.diveNr, order: sortOrder)]
    }

    var body: some View {
        let _ = updateSort()
        NavigationStack {

相关问题