FetchedResults to Array

So I have a core data entity titled recipe. I'm trying to make a search bar to search the list of recipes and my method of doing so is doing a fetch request of all objects and converting it to an array of those objects and then filtering the array and displaying the results. Any idea as to how to convert a type fetch results to an array?

PS: as I'm typing this it occurred to me I could just do a for each loop and add them to the array as I go, but is there a quicker way to do this? Like a function? Thanks!!!

Replies

Just to confirm you have an NSSet of objects and you can't turn it into an array, right? Getting an error/warning for Cast from 'NSSet?' to unrelated type '[EntityName]' always fails...

There's a parameter allObjects on, at least, the Core Data relationship NSSet that you can use to convert it to an array. In my case I use it when taken a set of Entities from a relationship. So:

FirstEntityName?.relationshipNameWithNSSet?.allObjects as? [SecondEntityName]

If they NEED a result I sometimes use ?? [SecondEntityName]() to create an empty default array.

  • So my FetchedResults is gotten from this:

    @FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)]) var recipes: FetchedResults<Recipe>

    and I need to put the data (list of recipes) from that into my array of recipes:

    @State private var searchArray = [Recipe]()
  • Gotcha. I haven't tried to directly cast before as I normally go through the relationships. With the fetchRequest I've use a for statement and a ForEach(fetchRequestResult, id: \.self) { item in with no issues. Good luck :)

Add a Comment