(Initially) getting duplicate results from FetchedObjects

1 week ago 16
ARTICLE AD BOX

I'm taking a class to try to learn iOS programming, and am working on a class project related to Core Data, filtering, and sorting. The class is doing a poor job teaching, but I'm close. I don't want anyone doing my project for me, but I think I'm stumped at debugging what I'm currently seeing.

It is a menu application. There is a function that fetches menu items from a Rest call and adds them to a Core Data entity. I feel pretty confident that is getting called and inserting 12 items into the Dish entity.

I have a view that attempts to let you view all the Dishes, it includes a search bar to narrow the search. When I first see that view loaded, it is showing 24 dishes; every dish is showing up twice. The code for that is:

NavigationView { FetchedObjects ( predicate:buildPredicate(), sortDescriptors: buildSortDescriptors() ) { (dishes: [Dish]) in List { Text(String(dishes.count) + " dishes") ForEach(dishes, id: \.self) { dish in DisplayDish(dish).onTapGesture {apGesture in self.showAlert.toggle() } } } } }.searchable(text: $searchText, prompt: "Search items")

(I included that Text with the dish count to help narrow what is happening, and it does indeed say there are 24 dishes upon first arriving at the view)

The predicate is built as follows:

private func buildPredicate() -> NSPredicate { if searchText.isEmpty { NSPredicate(value: true) } else { NSPredicate(format: "name CONTAINS[cd] %@", searchText) } }

I'm extremely open to the possibility I'm doing something wrong heh But here is the part that really throws me off: if I enter something into the search bar, it not only filters properly, it doesn't find any duplicates. That's a little weird. Now I clear out the search bar and stop searching, so I should be back to using the true predicate, and now it says there are 12 dishes and shows no duplicates. This all makes me think there really are only 12 Dishes in the entity, and narrows my focus to figuring out why that FetchObjects is returning 24 the first time the view is used.

I realize there is a lot of code that I didn't include; if I left out something that seems important/necessary I can augment. The only other thing that I noticed that seems like it could be relevant is that the function that loads the Dishes does indeed get called twice. But the first call to it gets an NSError of cancelled, presumably because the second one lands and supersedes it, and when the dust clears the loading function only actually saves once, and a query right afterwards shows 12 dishes, not 24.

Any help would be greatly appreciated.

Read Entire Article