I have been trying to get a master detail application working for too long. I've tried many things and nothing really seems to work. Part of my problem is that I don't know the best way to go about it.
I have a core data model created and I can add master items. I have a detail view in a tab view that should display the detail items for the global selected master (optional value on environment object data).
The questions I have are:
-
What is the best way to do a detail view with a list? Iterate over the master object's list of detail items or use a fetch request with a predicate for the master? The first way kinda seems to work but the list doesn't get updated when items are deleted. It's not clear to me how to do the predicates for the fetch request so I haven't figured that out yet.
-
When deleting detail items, how is this done? Do you delete from the master and then save? Do you delete the detail items and let core data take care of the master? Is there some other way?
-
Does anybody know of a decent example of this kind of thing. All the examples I found either don't do editing, don't use core data, etc.
I'm not posting code because I'm trying to figure out best practices and what is recommended by Apple.
Thanks.
hi,
first, you might start with something simple and straightforward: Paul Hudson's 100 Days of SwiftUI, specifically the BookWorm project which is Day 53 of the curriculum. look for these links:
- https://www.hackingwithswift.com/100/swiftui
- https://www.hackingwithswift.com/100/swiftui/53
the only thing missing from your list of requests is the ability to delete an item from within the detail view.
it's exactly because of this omission that i got started on my own project with Xcode 11 called ShoppingList (and then its iterations for ShoppingList14 with iOS 14 and Xcode 12, and now ShoppingList15 with iOS 15 and Xcode 13) that implemented (!) deletion from within the detail view. i've tried to comment extensively throughout the code to indicate issues i found in development, especially those that involve my eventual solution of many "did not update" issues most people run into.
you can find my current development at the following link, and as long as you are on the master branch (based on using @FetchRequests), you should find plenty of code to work with. (the MVVM branch in that project is not quite there yet, which does not use @FetchRequests.)
in answer to your question
What is the best way to do a detail view with a list? Iterate over the master object's list of detail items or use a fetch request with a predicate for the master?
i think you are better off "passing in" a Core Data object to a detail view (often as an @ObservedObject, despite the fact that in-detail-view deletion has a little bit of a twist to it) than making a fetch request.
hope that helps,
DMG