1

I try to remove some Persons from a FetchRequest, but the object itself is not removed and only the name property is empty. I load it like this:

var filteredPersons: FetchRequest<Person>

init() {
    let personFilterIds = ["1234", "2345", "3456"]
    filteredPersons = FetchRequest<Person>(
        entity: Person.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: \Person.name, ascending: false)],
        predicate: NSPredicate(format: "NOT (id IN %@)", personFilterIds)
    )
}

I then display the remaining Persons in this way:

var body: some View {
    ForEach(filteredPersons.wrappedValue, id: \.self) { person in
        // Why do I need this if to only display the filtered ones?
        // Why does the person object still exist in the list? (person.id is for example still there)
        if (!person.name.isEmpty) {
            Text(person.name)
        }
   }
}

Why is it not working correctly without the if (!person.name.isEmpty)? Am I doing the filtering wrong?

fer0n
  • 295
  • 1
  • 5
  • 14
  • You aren't returning the result of a fetch request. – El Tomato Jul 29 '21 at 07:34
  • How come it's displaying anything at all then? The problem is not that it's not showing the result, the problem is it's not filtering it correctly. And for that I am doing pretty much exactly [this](https://www.hackingwithswift.com/books/ios-swiftui/dynamically-filtering-fetchrequest-with-swiftui). Or do I not understand that right? @ElTomato – fer0n Jul 29 '21 at 07:54
  • Note that there isn’t anything dynamic about your fetch request so you don’t need to create it in the init. – Joakim Danielson Jul 29 '21 at 08:07
  • Your predicate will cause the fetch to return ALL the Person objects EXCEPT the three with the given ids. Are you sure there are no “old” Person objects with a nil name attribute? – pbasdf Jul 29 '21 at 17:14
  • @JoakimDanielson you're right, in the actual code the id list is dynamic tough – fer0n Jul 30 '21 at 05:45
  • @pbasdf yes, I am sure these are actually the Person objects that should be filtered. The "id" property for example is still there and if I turn off the predicate the same are shown with their name – fer0n Jul 30 '21 at 05:49
  • Could you try to declare and initialize the fetch request the same way as in [this answer](https://stackoverflow.com/a/58081279/9223839) to see if it works better? – Joakim Danielson Jul 30 '21 at 06:40
  • Out of interest, what happens if you invert the predicate (NSPredicate(format:”id IN %@“))? Do the items still show up, and is their name attribute still nil? – pbasdf Jul 30 '21 at 15:30

0 Answers0