I have a Category
(structure) Word
(structure) with a simple one to many
relationship defined between Category
and Word
i.e Category
has many Word
s.
I have a master detail style view setup using NavigationViews, the master view picks a list of Categories and displays them on a list.
struct CategoryView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Category.name, ascending: true)],
animation: .default)
private var categories: FetchedResults<Category>
var body: some View {
List {
Section {
ForEach(self.categories) { category in
NavigationLink(destination:
WordListView(title: category.name!,
words: category.words!.allObjects as! [Word])) {
Text("\(category.name!)")
}
}
}
}
.listStyle(InsetGroupedListStyle())
}
}
What I am wanting to do is pass the words
property (presumably Core Data will fetch these once it's accessed) to a child view to display a list of Word
s:
struct CategoryView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Category.name, ascending: true)],
animation: .default)
private var categories: FetchedResults<Category>
var body: some View {
List {
Section {
ForEach(self.categories) { category in
NavigationLink(destination:
WordListView(title: category.name!,
words: category.words!.allObjects as! [Word])) {
Text("\(category.name!)")
}
}
}
}
.listStyle(InsetGroupedListStyle())
}
}
Core Data makes the property available as a NSSet
, which I am converting to an Array
.
Is this al efficient thing to do? I feel like I am beating all the nice lazy loading Core Data would do.
Any suggestions out there on doing this better?
Thank you for your time.