[英]CoreData : Fetch Multiple Entities using NSFetchedResultController
[英]How do I use a Fetch Request for multiple entities in CoreData?
目標:我想按我已經完成的截止日期顯示Todo
列表。 但我還想在 Todo 項目列表上方的同一視圖中顯示不同實體的列表,即Categories
。 類別是用於將您帶到過濾到該類別的待辦事項列表的按鈕。 我將 Category 的關系設置為有很多待辦事項。 如何更改我的 FetchRequest 以支持添加的關系?
下面是當前的SectionedFetchRequest
。 如果我嘗試為類別添加新的 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>
這個你可能想多了。 如果您為類別添加sectionIdentifier
,您可以相對容易地提供該選項。
變量看起來像這樣
extension Todo{
@objc
var categoryTitle: String{
self.relationship?.title ?? "no category"
}
}
然后在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
}
})
}
然后給用戶一些按鈕到 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)
ForEach
將自動顯示用戶選擇
ForEach(filteredSections) { section in
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.