简体   繁体   English

如何对 CoreData 中的多个实体使用 Fetch Request?

[英]How do I use a Fetch Request for multiple entities in CoreData?

Goal: I want to to show a list of Todo items by their due dates which I have already achieved.目标:我想按我已经完成的截止日期显示Todo列表。 But I also wanna show a list of a different entity, Categories on the same View above the list of Todo items.但我还想在 Todo 项目列表上方的同一视图中显示不同实体的列表,即Categories The categories are buttons to take you to a list of todo items filtered to that category.类别是用于将您带到过滤到该类别的待办事项列表的按钮。 I set a relationship of Category to have many todos.我将 Category 的关系设置为有很多待办事项。 How do I change my FetchRequest to support the added relationship?如何更改我的 FetchRequest 以支持添加的关系?

Here is the current SectionedFetchRequest below.下面是当前的SectionedFetchRequest If I try to add a new FetchRequest for Categories I get a crash.如果我尝试为类别添加新的 FetchRequest,我会崩溃。

    @SectionedFetchRequest(entity: Todo.entity(),
                           sectionIdentifier: \.dueDateRelative,
                           sortDescriptors: [NSSortDescriptor(keyPath: \Todo.dueDate, ascending: true)],
                           predicate: nil,
                           animation: Animation.linear)
    var sections: SectionedFetchResults<String, Todo>
                    ForEach(sections) { section in
                        Section(header: Text(section.id.description)) {
                            ForEach(section) { todo in
                                TodoRowView(todo: todo)
                                    .frame(maxWidth: .infinity)
                                    .listRowSeparator(.hidden)
                            }
                            .onDelete { indexSet in
                                deleteTodo(section: Array(section), offsets: indexSet)
                            }
                        }
                    }
// Causes Crash when added to existing Fetch Request
//@FetchRequest(entity: Category.entity(), sortDescriptors: []) var categories: FetchedResults<Category>

在此处输入图像描述

在此处输入图像描述

You might be overthinking this.这个你可能想多了。 If you add a sectionIdentifier for the category you can offer the option relatively easy.如果您为类别添加sectionIdentifier ,您可以相对容易地提供该选项。

The variable would look like this变量看起来像这样

extension Todo{
    @objc
    var categoryTitle: String{
        self.relationship?.title ?? "no category"
    }
}

Then add a few variables to the View然后在View中添加一些变量

//Dictionary to store sort options
let sortOptions: [String: KeyPath<Todo, String>] = ["due date": \Todo.dueDateRelative, "category":\Todo.categoryTitle]
//Variable to use to filter list
@State var selectedSection: String = ""
//filter the `sections` by the selected section
//You can use nsPredicate too
var filteredSections: [SectionedFetchResults<String, Todo>.Element] {
    sections.filter({ val in
        if !selectedSection.isEmpty {
            return val.id == selectedSection
        }else{
            return true
        }
    })
}

Then give the user some buttons to select然后给用户一些按钮到 select

//Give the user sort options
Menu("sort"){
    ForEach(Array(sortOptions.keys).sorted(by: <), id:\.self, content: { key in
        Button(key, action: {
            sections.sectionIdentifier = sortOptions[key]!
            selectedSection = ""
        })
    })
}
//Give the user section options
Picker("sections", selection: $selectedSection, content: {
    ForEach(sections, content: {section in
        Text(section.id).tag(section.id)
    })
    Text("all").tag("")
}).pickerStyle(.segmented)

The ForEach would display the user selections automatically ForEach将自动显示用户选择

ForEach(filteredSections) { section in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM