在.onAppear初始化CoreData对象

时间:2020-10-06 03:48:50

标签: core-data swiftui

对于我来说,我想将AppStorage传递给谓词以动态过滤@FetchRequest,但我也想在过滤之前获取CoreData对象。

但是当我运行代码时,会出现错误

displayModeButtonItem由内部管理,不针对DoubleColumn样式公开。返回一个空的,断开连接的UIBarButtonItem来履行非空合同

表明执行fetchSubItems时,筛选器在SecondListDetailView中不起作用。

struct OneListSelectView: View {
    @AppStorage("filter") private var filter = ""
    ...
    
    var body: some View {
        List {
            ForEach(items) { item in
                NavigationLink(destination: SecondListDetailView(filter: filter)) {
                    Button(action: {
                        filter = item.subId!
                    })
    ...
}

struct SecondListDetailView: View {
    @AppStorage("filter") private var filter = ""
    @AppStorage("subFilter") private var subFilter = ""
    @Environment(\.managedObjectContext) private var viewContext
    var fetchRequest: FetchRequest<SubItem>
    var subItems: FetchedResults<SubItem> { fetchRequest.wrappedValue }
    
    var body: some View {
        List {
            ForEach(subItems) { subItem in
                NavigationLink(destination: ThirdSubListDetailView(filter: subFilter)) {
                    Button(action: {
                        subFilter = subItem.id!
                    }) {
                        Text(subItem.id!)
                    }
                }
            }
        }
        .onAppear(perform: fetchSubItems)
    }

    init(filter: String) {
        fetchRequest = FetchRequest<SubItem>(entity: SubItem.entity(), sortDescriptors: [], predicate: NSPredicate(format: "subItem_id = %@", filter))
    }
    ...
}

0 个答案:

没有答案